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

convert a list of strings of ints to list of tuples

如果我有一个看起来像下面这样的字符串列表:

['10 90', '10 -90', '100 45', '20 180']

如何将其转换为元组列表?像这样:

[(10,90), (10,-90), (100,45), (20,180)]

下面的代码不会更改原始列表,因为我认为 Python 中的列表是可变的,我可以直接更改值而不是创建正确值的新列表。什么是最好的方法?

newlines = []
for string in lines:
    newlines.append(tuple(string))

打印:

[('1', '0', ' ', '9', '0'), ('1', '0', ' ', '-', '9', '0'), ('1', '0', '0', ' ', '4', '5'), ('2', '0', ' ', '1', '8', '0')]

您必须先拆分每个字符串。然后将每个拆分项转换为整数;最后将对转换为元组:

out = [tuple(map(int, item.split())) for item in lst]

输出:

[(10, 90), (10, -90), (100, 45), (20, 180)]

您可能可以通过映射和列表理解来完成,但为了清楚起见,让我们使用简单的循环:

values=['10 90', '10 -90', '100 45', '20 180']
result=[]
for x in values:
    pair=x.split()
    pair=tuple(map(int, pair))
    result.append(pair)
print(result)

你可以试试这个,应该给你相同的结果,old_lst 是你想要转换的列表。您还应该使用 item.partition(' ') 获得类似的结果,但您必须合并额外的步骤才能在返回的数据中弹出 space。

old_lst = ['10 90', '10 -90', '100 45', '20 180']
new_lst = []

for item in old_lst:
    pair=item.split(' ')
    new_lst.append(tuple(pair))

结果:

[('10', '90'), ('10', '-90'), ('100', '45'), ('20', '180')]