Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python附加到列表中的字符串元素_Python - Fatal编程技术网

Python附加到列表中的字符串元素

Python附加到列表中的字符串元素,python,Python,我对python相当陌生。我想知道如何在列表中累积附加到字符串元素 list = ['1','2','3','4'] list2 = ['a','b','c','d'] 我想要一个这样的新列表: list3 = ['1a', '1b', '1c', '1d'] letters = [ 'a', 'b', 'c', 'd' ] numberedLetters = [] for i in range (len(letters)): numberedLetters += [ str(i+

我对python相当陌生。我想知道如何在列表中累积附加到字符串元素

list = ['1','2','3','4']
list2 = ['a','b','c','d']
我想要一个这样的新列表:

list3 = ['1a', '1b', '1c', '1d']
letters = [ 'a', 'b', 'c', 'd' ]
numberedLetters = []

for i in range (len(letters)):
    numberedLetters += [ str(i+1) + letters[ i ] ]

print numberedLetters
我一直在绕圈子寻找可能的答案。非常感谢您的帮助,谢谢

使用。请注意,您需要通过
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']
您可以这样使用:

输出:

['1a', '2b', '3c', '4d']

在线演示-在您的问题中,您需要
列表3=['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']
>>> 

我假设你的目标是[‘1a’、‘2b’、‘3c’、‘4d’]

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
不过,总的来说,我会谨慎行事。这里并没有检查列表的长度是否相同,所以如果列表比列表2长,就会出现错误,如果列表比列表2短,就会丢失信息

我会这样做这个具体的问题:

list3 = ['1a', '1b', '1c', '1d']
letters = [ 'a', 'b', 'c', 'd' ]
numberedLetters = []

for i in range (len(letters)):
    numberedLetters += [ str(i+1) + letters[ i ] ]

print numberedLetters

与其他海报一样,不要将变量命名为“列表”——不仅因为它是一个关键字,而且因为变量名称应该尽可能提供信息。

对不起,输入错误,是有字符串的。您想要
list3=['1a',1b',1c',1d']
还是
list3=['1a',2b',3c',4d']
?您的结果有点误导。您想用列表2的所有元素作为
1
的前缀,还是相邻的连接?您确定要
['1a',1b',1c',1d']
而不是
['1a',2b',3c',4d']
?虽然代码本身就可以说明问题,但最好给代码添加一些解释。