如何在列表变量之间添加字符串?

2024-06-28 19:08:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我想加上“!”在列表中的每个变量之后。 但我的代码只添加了“!”在初始列表之后。 例如:

lst = [1,2,3,4]

def addmark(lst):
    emptylst = []
    for n in range(0, len(lst)):
        lst.append("!")
    return lst

这将返回[1,2,3,4,“!”, "!", "!", "!"]你知道吗

我要转[1,“!”, 2, "!", 3, "!", 4, "!"]你知道吗


Tags: 代码in列表forlenreturndefrange
3条回答

使用插入:

list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

引用:docs.python.org/2/tutorial/datastructures

代码:

def addmark(lst):
    add = 0 # needed cause after every insertion of '!' the position where you want to add the next '!' changes
    for i in range (1,len(lst)+1): # (start: adding after ls[0], finish: adding after the last element)
        lst.insert(i+add, '!')
        add += 1
    return lst
def addmark(lst):
    emptylst = []
    for i in lst:
        emptylst.append(i)
        emptylst.append("!")
    return emptylst

使用itertools替代公认答案的方法:

from itertools import chain, repeat

lst = [1, 2, 3]
marker = repeat("!")

list(chain.from_iterable(zip(lst, marker)))
>>> [1, '!', 2, '!', 3, '!']

相关问题 更多 >