Warm tip: This article is reproduced from stackoverflow.com, please click
add list python string

Join text to several multi-level lists in Python

发布于 2020-03-27 10:14:58

Using Python, I have a bunch of lists I want to join some text to. These lists have multi-level entries (or whatever term it is used to describe it), like this:

    ['def', 'ghi'])
    ['456', '789'])

I would like to join the string 'X' to each element of both lists:

    ['Xdef', 'Xghi'])
    ['X456', 'X789'])

I just can't do it neatly. I did some 'for loops' but it seems incredibly poor, and not reproducible, considering I have several lists:

for index, item in enumerate(list1):
    for index2, item2 in enumerate(item):
        list1[index][index2] = "X" + item2

for index, item in enumerate(list2):
    for index2, item2 in enumerate(item):
        list2[index][index2] = "X" + item2

I know this should be a one liner. I found some answers for single simple lists but the ones I have contain multi-level (multi-elements?) and there is more than one list:

list = ["X" + string for string in list]

I just can't adapt this. Any thoughts? Thanks in advance.

FredMan 2019-07-03 21:47

You may be interested to learn about slice assignment, if you were concerned about all the indexes you were creating with enumeration and what not.

for b in list1 :
    b[:]= ["X"+a for a in b]

Though technically this doesn't do assignment in place (it creates a list for the list comprehension) it will effectively update list1 directly, and doesn't require you to then assign list1 = [list comprehension]

If you want to actually supply individual parameters you would use star to pack the variables into a list.

def update_lists(prepend_text, *lists) :
    for list in lists :
        update_list(prepend_text, list)

def update_list(prepend_text, list) :
    for b in list :
        b[:]= [prepend_text+a for a in b] 
update_lists("X", list1,list2)

Alternatively you can define the function like this:

def update_lists(prepend_text, lists) :
    for list in lists :
        update_list(prepend_text, list)

and then call the function as

update_lists("X", [list1,list2])

or perhaps better if you create the list of lists dynamically

lists = []
update_lists("X", lists)