简体   繁体   中英

How to add String in-between list variables?

I am trying to add "!" after every variable in a list. But my code only adds the series of "!" after the initial list. For example:

lst = [1,2,3,4]

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

This would return [1,2,3,4,"!", "!", "!", "!"]

I want to reuturn [1, "!", 2, "!", 3, "!", 4, "!"]

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

An alternative to the accepted answer using itertools:

from itertools import chain, repeat

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

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

Using insert:

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).

Reference: docs.python.org/2/tutorial/datastructures

Code:

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

this is code

#!/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)

create a list of lists then flatten

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, '!']

as a one liner:

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, '!']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM