OK 400
OK 400

Reputation: 831

Splitting a list and getting 2 variables

I have a list like this:

A = [['1-2'], ['10-0'], ['1-4'], ['7-20'], ['10-255'], ['10000-21']]

I have seen that there are similar questions but I can't solve this with that helps... I would like to split each one of them in 2 variables, resulting at this:

var1 = [1, 10, 1, 7, 10, 10000]
var2 = [2, 0, 4, 7, 20, 255, 21]

Upvotes: 0

Views: 56

Answers (2)

yatu
yatu

Reputation: 88226

You could split those strings in a list comprehension, and unpack them into separate lists with zip:

var1, var2 = map(list,zip(*(map(int,s[0].split('-')) for s in A)))

print(var1)
# [1, 10, 1, 7, 10, 10000]
print(var2)
# [2, 0, 4, 20, 255, 21]

zip is useful here, since it helps us get from:

l = [list(map(int,s[0].split('-'))) for s in A]
print(l)
[[1, 2], [10, 0], [1, 4], [7, 20], [10, 255], [10000, 21]]

To:

list(zip(*l))
# [(1, 10, 1, 7, 10, 10000), (2, 0, 4, 20, 255, 21)]

And then we can unpack both lists into var1 and var2. I'm mapping them to lists, but if tuples work this would be enough.

Upvotes: 2

badhusha muhammed
badhusha muhammed

Reputation: 491

Try This:

  var1 = [int(x[0].split("-")[0]) for x in A]
  var2 = [int(x[0].split("-")[1]) for x in A]

Upvotes: 0

Related Questions