将字符串列表转换为整数元组

Convert list of strings into tuple of integers

我需要将包含 2 个项目的字符串(用逗号分隔)转换为整数。还需要将列表的列表切换为元组的元组。

来自:

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

至:

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

我该怎么做?

谢谢。

您可以将映射和元组与列表理解混合使用:

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

输出:

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

说明:map用于在split的输出上将元素转换为int,即内部列表的元素。 tuple 用于根据需要将类型转换为 tuple

您可以使用标准的“累加器模式”:

# 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),)

首先,inner_list[0]给出内部列表中的字符串,例如:"0,1"。接下来,.split(",") 在逗号字符处拆分该字符串,生成一个字符串列表:["0", "1"]。然后,a, b = ... 将列表“解包”为变量 ab。最后,我们将 ab 转换为 int 并将其作为元组 的 元组添加到 outer_tuple (我们的累加器) .

我们需要这样做的原因 ((a, b),) 是因为当你添加两个元组时,你实际上只是在做一个联合,或者换句话说,你从两个元组中获取元素并创建一个包含所有元素的新元组:

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

但这不是我们想要的。我们想要一个元组的元组。看看会发生什么:

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

一个简单的方法:

>>> 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))

希望对您有所帮助:

首先,我们将为输出制作一个列表,然后我们将遍历输入列表中的每个元素,然后制作它的元组版本,元组版本将通过用逗号和然后使用 map 函数获取一个元组版本,该版本具有 int 类型而不是 string 类型。然后将其附加到输出列表。最后将输出列表转换为元组。

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)