[英]Add string to end of every tuple in a list of tuples
I have this list of tuples; 我有这个元组列表;
List = [('1', 'John', '129', '37'), ('2', 'Tom', '231', '23')]
I want to add a string to the end of every tuple inside this list. 我想在此列表中每个元组的末尾添加一个字符串。 It will look like this;
看起来像这样;
OutputList = [('1', 'John', '129', '37', 'TestStr'), ('2', 'Tom', '231', '23', 'TestStr')]
I tried OutputList = [xs + tuple('TestStr',) for xs in List ]
but it did not work out. 我试过
OutputList = [xs + tuple('TestStr',) for xs in List ]
但没有成功。 What is the proper way to solve this? 解决此问题的正确方法是什么?
I am using Python 2.7 我正在使用Python 2.7
If you want a 1-element tuple, that's ('TestStr',)
, not tuple('TestStr',)
: 如果要使用1元素元组,
('TestStr',)
,而不是tuple('TestStr',)
:
OutputList = [xs + ('TestStr',) for xs in List]
tuple('TestStr',)
is the same as tuple('TestStr')
, since trailing commas are ignored in function calls. tuple('TestStr',)
与tuple('TestStr')
,因为尾部逗号在函数调用中被忽略。 tuple('TestStr')
treats 'TestStr'
as an iterable and builds a tuple containing the characters of the string. tuple('TestStr')
将'TestStr'
视为可迭代对象,并构建一个包含字符串字符的元组。
Just remove the tuple
part: 只需删除
tuple
部分:
OutputList = [xs + ('TestStr',) for xs in List]
You don't need to the tuple()
callable here, you are not converting one type to a tuple, all you need is a tuple literal here. 您不需要此处可调用的
tuple()
,无需将一种类型转换为元组,这里只需要一个元组文字即可。
Demo: 演示:
>>> List = [('1', 'John', '129', '37'), ('2', 'Tom', '231', '23')]
>>> [xs + ('TestStr',) for xs in List]
[('1', 'John', '129', '37', 'TestStr'), ('2', 'Tom', '231', '23', 'TestStr')]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.