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

时间:2017-03-19 01:04:01

标签: 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,“!”]

5 个答案:

答案 0 :(得分:3)

def addmark(lst):
    emptylst = []
    for i in lst:
        emptylst.append(i)
        emptylst.append("!")
    return emptylst

答案 1 :(得分:2)

使用itertools替代已接受的答案:

from itertools import chain, repeat

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

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

答案 2 :(得分:1)

使用insert:

  

列表。插入 (i,x)
  在给定位置插入项目。首先   argument是要插入的元素的索引,所以   a.insert(0,x)插入列表的前面,a.insert(len(a),   x)相当于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

答案 3 :(得分:0)

这是代码

#!/usr/bin/env python
# coding:utf-8

'''黄哥Python'''


def addmark(lst):
    result = []
    for i, item in enumerate(lst):
        result.append(item)
        result.append("!")
    return result


if __name__ == '__main__':
    lst = [1,2,3,4]
    print addmark(lst)

答案 4 :(得分:0)

创建列表列表然后展平

lst = [1,2,3,4]
lst2 = [[i,'!'] for i in lst]
lst3 = [item for sublist in lst2 for item in sublist]
print lst2
print lst3    

>>> [[1, '!'], [2, '!'], [3, '!'], [4, '!']]
>>> [1, '!', 2, '!', 3, '!', 4, '!']

作为一个班轮:

lst = [1,2,3,4]
lst2 = [item for sublist in [[i,'!'] for i in lst] for item in sublist]
print lst2

>>> [1, '!', 2, '!', 3, '!', 4, '!']