Reputation: 111
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
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
Upvotes: 0
Views: 121
Reputation: 105
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]
Upvotes: 2
Reputation: 71
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'
Upvotes: 0
Reputation: 174706
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'
>>>
Upvotes: 3