简体   繁体   中英

Convert list of strings into tuple of integers

I need to convert a string of 2 items (separated by a comma) to integers. Also need to switch the list of lists into a tuple of tuples.

from:

[['0,0'], ['0,1'], ['1,-1'], ['1,0']]

to:

((0,0), (0,1), (1,-1), (1,0))

How can I do that?

Thanks.

You can use mix of map and tuple with list comprehension as:

x = [['0,0'], ['0,1'], ['1,-1'], ['1,0']]
x = tuple([tuple(map(int, elt[0].split(','))) for elt in x])
print(x)

Output:

((0, 0), (0, 1), (1, -1), (1, 0))

Explanation: map is used to convert the elements to int on the output of split which is the elements of the inner list. The tuple is used to convert the types to tuple as required.

You can use the standard "accumulator pattern":

# Initialize an accumulator
outer_tuple = tuple()

for inner_list in outer_list:
    a, b = inner_list[0].split(",")
    a, b = int(a), int(b)
    outer_tuple += ((a, b),)

First, inner_list[0] gives the string inside the inner list, eg: "0,1" . Next, .split(",") splits that string on the comma character, which produces a list of strings: ["0", "1"] . Then, a, b =... "unpacks" the list into the variables a and b . Finally, we cast a and b to int and add it as a tuple of tuples to the outer_tuple (our accumulator).

The reason we need to do ((a, b),) is because when you add two tuples, you're really just doing a union, or in other words, you're taking the elements from both tuples and creating a new tuple with all the elements:

>>> x = (1, 2)
>>> y = (3, 4)
>>> x + y
(1, 2, 3, 4)

But that's not what we want. We want a tuple of tuples. Watch what happens:

>>> x += y
>>> x
(1, 2, 3, 4)
>>> x += ((5, 6),)
>>> x
(1, 2, 3, 4, (5, 6))

Hope this helps:

First, we will make a list for the output, then we will iterate through every element in the input list and then make a tupled version of it, the tupled version would be made by spliting the string by the comma and then use the map function to get a tupled version which would have int type rather then string. Then append that to the output List. At last convert the output list into a tuple.

inputGiven = [['0,0'], ['0,1'], ['1,-1'], ['1,0']]
outputGivenInList = []
for i in inputGiven:
    tupledVersion = tuple(map(int, i[0].split(",")))
    outputGivenInList.append(tupledVersion)
finalOutput = tuple(outputGivenInList)
print(finalOutput)

A simple way:

>>> tmp = tuple(eval(str(li).replace('\'', '')))
>>> ans = (tuple(tmp[i]) for i in range(4))
>>> ans
<generator object <genexpr> at 0x000001754697D8C8>
>>> tuple(ans)
((0, 0), (0, 1), (1, -1), (1, 0))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM