0

I have a list in python :

['ABCD_BAND1.TXT', 'ABCD_BAND2.TXT', 'ABCD_BAND3.TXT', 'ABCD_BAND4.TXT', 'ABCD_BAND5.TXT', 'ABCD_BAND6.TXT', 'ABCD_BAND7.TXT'] 

I want to pick ABCD_BAND4.TXT & ABCD_BAND5.TXT and define them as two new variables and do my analysis based on these two variables. I have written the following code but it does not works

Assign Variables

dataList = ['ABCD_BAND1.TXT', 'ABCD_BAND2.TXT', 'ABCD_BAND3.TXT', 'ABCD_BAND4.TXT', 'ABCD_BAND5.TXT', 'ABCD_BAND6.TXT', 'ABCD_BAND7.TXT']
for item in dataList:
    if item.endswith("BAND4.TXT"):
        Item = "band4"
for item in dataList:
    if item.endswith("BAND5.TXT"):
        Item = "band5"

How can I fix it?

Cheers

2
  • 1
    What seems to be the problem with this? Item is first set to "band4" in the first loop and then Item is set to "band5" in the second loop. Do you just need to use two different names, say item1 and item2? Commented Sep 9, 2015 at 3:59
  • How do you know it doesn't work? Commented Sep 9, 2015 at 4:59

3 Answers 3

3

You need to declare two separate variables for storing the returned output.

>>> s = ['ABCD_BAND1.TXT', 'ABCD_BAND2.TXT', 'ABCD_BAND3.TXT', 'ABCD_BAND4.TXT', 'ABCD_BAND5.TXT', 'ABCD_BAND6.TXT', 'ABCD_BAND7.TXT']

>>> item4 , item5 = "",""
>>> for i in s:
        if i.endswith("BAND4.TXT"):
            item4 = i
        elif i.endswith("BAND5.TXT"):
            item5 = i

>>> item4
'ABCD_BAND4.TXT'
>>> item5
'ABCD_BAND5.TXT'
>>> 
Sign up to request clarification or add additional context in comments.

Comments

2

You can use result_list depend on your purpose.

raw_list = ['ABCD_BAND1.TXT', 'ABCD_BAND2.TXT', 'ABCD_BAND3.TXT','ABCD_BAND4.TXT', 'ABCD_BAND5.TXT', 'ABCD_BAND6.TXT', 'ABCD_BAND7.TXT']

chose_list =  ['ABCD_BAND4.TXT', 'ABCD_BAND5.TXT']

result_list = [item for item in raw_list if item in chose_list] 

Comments

0

this solution works for me

>>> DataList = ['ABCD_BAND1.TXT', 'ABCD_BAND2.TXT', 'ABCD_BAND3.TXT', 'ABCD_BAND4.TXT', 'ABCD_BAND5.TXT', 'ABCD_BAND6.TXT', 'ABCD_BAND7.TXT']

>>> band4 = [i for i in DataList if "BAND4.TXT" in i][0] # 0 index for first occurance in list
>>> band4 
'ABCD_BAND4.TXT'
>>> band5 = [i for i in DataList if "BAND5.TXT" in i][0] # 0 index for first occurance in list
>>> band5
'ABCD_BAND5.TXT'

2 Comments

Looping through the array twice is not exactly efficient.
I have just improved authors code to work, and there was no efficiency requirement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.