[英]Convert a list of strings to a list of tuples in python
我有一个这种格式的字符串列表:
['5,6,7', '8,9,10']
我想将其转换为以下格式:
[(5,6,7), (8,9,10)]
到目前为止,我已经尝试过:
[tuple(i.split(',')) for i in k]
我得到:
[('5','6','7'), ('8','9','10')]
我有点坚持如何简单地将字符串转换为整数元组。 谢谢
如果您的字符串是数字的字符串表示形式,则:
[tuple(int(s) for s in i.split(',')) for i in k]
以下解决方案对我来说是最易读的,也许对其他人来说也是如此:
a = ['5,6,7', '8,9,10'] # Original list
b = [eval(elem) for elem in a] # Desired list
print(b)
回报:
[(5, 6, 7), (8, 9, 10)]
这里的关键点是内置的eval()
函数,它将每个字符串转换为一个元组。 但请注意,这仅在字符串包含数字时才有效,但如果给定字母作为输入,则会失败:
eval('dog')
NameError: name 'dog' is not defined
您的问题需要对元素进行分组。 因此,适当的解决方案是:
l = ['5','6','7', '8','9','10']
[(lambda x: tuple(int(e) for e in x))((i,j,k)) for (i, j, k) in zip(l[0::3], l[1::3], l[2::3])]
这输出:
[(5, 6, 7), (8, 9, 10)]
如预期的。
listA = ['21, 3', '13, 4', '15, 7']
# Given list
print("Given list : \n", listA)
# Use split
res = [tuple(map(int, sub.split(', '))) for sub in listA]
# Result
print("List of tuples: \n",res)
来源: https ://homiedevs.com/example/python-convert-list-of-strings-to-list-of-tuples#64288
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.