我有一个类似的列表:
mylist = ["1", "2", "3", "4", "5"]
我想在其他所有项目中添加一些文本,因此看起来像这样:
mylist = ["1a", "2", "3a", "4", "5a"]
我写了这个,对每个项目都很好。如何使它仅适用于所有其他项目?
mylist2 = ["a" + item for item in mylist]
答案 0 :(得分:10)
做到这一点的一种方法是:
mylist = ["1", "2", "3", "4", "5"]
res = [x + ('a' if i%2 == 0 else '') for i, x in enumerate(mylist)]
结果为:
['1a', '2', '3a', '4', '5a']
这种方法利用了一个事实,即要除以2时要更改的术语的索引的余数为1。请参见modulo
答案 1 :(得分:10)
尝试一下:
for i in range(0, len(mylist), 2):
mylist[i] = mylist[i] + "a"
编辑1:
for i in range(0, len(mylist), 2):
mylist[i] += "a"
答案 2 :(得分:6)
使用enumerate
和模以三进制测试奇数或偶数。
mylist = ["1", "2", "3", "4", "5"]
mylist2 = [item if i%2 else "a" + item for i,item in enumerate(mylist)]
结果:
>>> mylist2
['a1', '2', 'a3', '4', 'a5']
获取1a
等...只需通过"a" + item
切换item + "a"
答案 3 :(得分:4)
有点奇怪的解决方案,它使用了迭代器:
>>> from itertools import cycle
>>> mylist = ["1", "2", "3", "4", "5"]
>>> suffix = cycle(["a", ""])
>>> [l + s for l, s in zip(mylist, suffix)]
['1a', '2', '3a', '4', '5a']
编辑
正如Netwave在评论中建议的那样,这是一个非常超Python的解决方案!
>>> import itertools, operator
>>> list(map(operator.add, mylist, itertools.cycle(("a", ""))))
['1a', '2', '3a', '4', '5a']
答案 4 :(得分:0)
mylist = ["1", "2", "3", "4", "5"]
text_list = [str(x) + 'a' if i % 2 == 0 else x for i, x in enumerate(mylist)]