Python将列表插入列表

时间:2017-09-13 14:37:19

标签: python list

我有一个这样的清单:

a = ["a","b","c","d","e"]

如何在列表中的每个项目的末尾插入一个单词并将其作为列表本身?

预期产出:

a = [("a","TEST"),("b","TEST"),("c","TEST"),("d","TEST"),("e","TEST")]

我尝试了很多方法,但没有运气。

4 个答案:

答案 0 :(得分:9)

创建一个包含项目和所需单词的元组:

word = "TEST"
a = ["a","b","c","d","e"]
new_a = [(i, word) for i in a]

输出:

[('a', 'TEST'), ('b', 'TEST'), ('c', 'TEST'), ('d', 'TEST'), ('e', 'TEST')]

或者,使用map

new_a = list(map(lambda x: (x, "TEST"), a))

答案 1 :(得分:2)

另一种方法是使用itertools模块中的zip_longest,如下所示(但是在列表解析中使用元组的解决方案应该是Ajax1234's):

from itertools import zip_longest

l = ['a', 'b', 'c', 'd', 'e']
res = list(zip_longest(l, ['TEST'], fillvalue='TEST'))

<强>输出:

>>> res
[('a', 'TEST'), ('b', 'TEST'), ('c', 'TEST'), ('d', 'TEST'), ('e', 'TEST')]

答案 2 :(得分:1)

您可以使用zip

a = ["a","b","c","d","e"]
new_a = zip(a, ["TEST"] * len(a))

输出:

[('a', 'TEST'), ('b', 'TEST'), ('c', 'TEST'), ('d', 'TEST'), ('e', 'TEST')]

答案 3 :(得分:1)

不是很时髦,但与其他常见语言类似:

a = ["a","b","c","d","e"]
b = []

for x in a:
    b.append ( (x, 'TEST'))

a = b

print a