我对python很新。我想知道如何累积地追加列表中的字符串元素?
list = ['1','2','3','4']
list2 = ['a','b','c','d']
我想要一个像这样的新列表:
list3 = ['1a', '1b', '1c', '1d']
我一直在圈子里寻找可能的答案。非常感谢帮助,谢谢!
答案 0 :(得分:2)
使用list comprehension。请注意,您需要通过str()
函数将整数转换为字符串,然后您可以使用字符串连接来组合list1 [0]和list2中的每个元素。另请注意,list
是python中的关键字,因此它不是变量的好名称。
>>> list1 = [1,2,3,4]
>>> list2 = ['a','b','c','d']
>>> list3 = [str(list1[0]) + char for char in list2]
>>> list3
['1a', '1b', '1c', '1d']
答案 1 :(得分:2)
list = ['1','2','3','4']
list2 = ['a','b','c','d']
print map(lambda x: x[0] + x[1],zip(list,list2))
输出:
['1a', '2b', '3c', '4d']
在线演示 - https://repl.it/CaTY
答案 2 :(得分:1)
在您的问题中,您需要list3 = ['1a', '1b', '1c', '1d']
。
如果你真的想要这个:list3 = ['1a', '2b', '3c', '4d']
那么:
>>> list = ['1','2','3','4']
>>> list2 = ['a','b','c','d']
>>> zip(list, list2)
[('1', 'a'), ('2', 'b'), ('3', 'c'), ('4', 'd')]
>>> l3 = zip(list, list2)
>>> l4 = [x[0]+x[1] for x in l3]
>>> l4
['1a', '2b', '3c', '4d']
>>>
答案 3 :(得分:-2)
我假设你的目标是[' 1a',' 2b',' 3c',' 4d' ]?
string[] lines = File.ReadAllLines("textfilename.txt");
for(int i = 0; i < lines.Length; i++)
{
string line = lines[i];
//Do whatever you want here
}
总的来说,我要小心这样做。这里没有检查列表的长度是否相同,因此如果列表长于list2,则会出现错误,如果列表比list2短,则您会错过信息。< / p>
我会这样做这个具体的问题:
list = [ '1', '2', '3', '4' ]
list2 = [ 'a', 'b', 'c', 'd' ]
list3 = []
for i in range (len(list)):
elem = list[i] + list2[i]
list3 += [ elem ]
print list3
并同意其他海报,不要将您的变量命名为&#39; list&#39; - 不仅因为它是一个关键词,而且因为变量名称应尽可能提供信息。