Reputation: 39
I have multiple list in the form of WAT2_005= ['1317.85 1344.47" spec4 = "4 61 0 9478.0172299001 0.12425255236787 20']
. The only common aspect in all of the list is the number 0. The two numbers that I need from the list happens to appear just after the number 0 in all of the list. For example, in the list provided above, the two numbers after 0 are 9478.0172299001
and 0.12425255236787
. How can I create a loop that goes through the list and only selects the two numbers it encounters after the 0 and stores in a new list?
Upvotes: 0
Views: 1503
Reputation: 42139
You can first split each string on " 0 " to capture the part that comes after that lone zero. Then split again on spaces to pick the next two values and use map to convert them into floats.
Since your string is within a list, I'm assuming you probably have multiple such string in your actual data and want a pair of number for each of them (otherwise don't enclose the string in a list):
WAT2_005=['1317.85 1344.47" spec4 = "4 61 0 9478.0172299001 0.12425255236787 20']
nums = [ [*map(float,S.split(" 0 ",1)[-1].split(" ")[:2])] for S in WAT2_005]
[[9478.0172299001, 0.12425255236787]]
Upvotes: 0
Reputation: 1455
find()
to get the index of the 0. Then added 2 to this
index to get starting position of the number.Then we can split('')
the string and create a new list.
WAT2_005= ['1317.85 1344.47" spec4 = "4 61 0 9478.0172299001 0.12425255236787 20']
for element in WAT2_005:
indx = element.find('0')+2
new_str = element[indx:]
lst = list(new_str.split(' '))
print(lst)
Upvotes: 0
Reputation: 352
Because your list is a string you have to split it first. You can then use the .index function to get the index of the zero and just add 2 to get the other too numbers. Here is an example:
WAT2_005= ['1317.85 1344.47" spec4 = "4 61 0 9478.0172299001 0.12425255236787 20']
l = WAT2_005[0].split(" ")
index = l.index("0")
values = (l[index +1], l[index +2])
That should give you the values you need. You can use any variable names I just did some random ones.
Upvotes: 1