[英]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))
我怎样才能做到这一点?
谢谢。
您可以将 map 和具有列表理解的元组混合使用:
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))
说明: map
用于将元素转换为int
的split
是内部列表的元素。 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 =...
将列表“解包”到变量a
和b
中。 最后,我们将a
和b
转换为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))
希望这可以帮助:
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获得一个具有 int 类型而不是字符串的元组版本。 然后 append 到 output 列表。 最后将 output 列表转换为元组。
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)
一个简单的方法:
>>> 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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.