Reputation: 183
I currently have a list that looks like the following:
list = ['325 153\n', '509 387\n', '419 397\n']
I am wondering how could i access these strings individually so i could use it in a function such as
for (x, y) in list:
where x is the first number of the string and y is the second number (separated by the space)
Is a good way to do this to turn the string into tuples somehow? I have tried using the 'split' function as i believe it is not valid for a list.
Upvotes: 0
Views: 68
Reputation: 14369
There is the split()
method for string. Before using it you should use strip()
to get rid of the training \n
. At the end you can put both into a list comprehension:
for x, y in [item.strip().split(" ", 1) for item in lst]:
Note that I replace list
with lst
. list
is a built-in type and should not be used as variable name.
Upvotes: 1
Reputation: 976
[tuple(x.split()) for x in list]
this will return you a list of tuples
Upvotes: 1
Reputation: 26667
>>> a_list = ['325 153\n', '509 387\n', '419 397\n']
>>> [ i.split() for i in a_list ]
[['325', '153'], ['509', '387'], ['419', '397']]
Upvotes: 3
Reputation: 1422
You can iterate one the elements of the list:
for elem in list:
a, b = elem.split()[0], elem.split()[1]
a and b will be the elements and you can process them just as you wish.
Upvotes: 1