简体   繁体   中英

How to merge elements of nested list for specific words

Really hoping someone can help with what is probably an easy issue but am struggling as a newbie to python.

I have the below nested list:

[['bob', 'smith', 'green'],
['jon', 'mc', 'donnell', 'red'],
['fred', 'thomas', 'blue'],
['jim', 'mc', 'donald', 'orange']]

I would like to iterate over it to end with something like the below to write to csv to open in excel:

[['bob', 'smith', 'green'],
['jon', 'mcdonnell', 'red'],
['fred', 'thomas', 'blue'],
['jim', 'mcdonald', 'orange']]

I have tried a for loop with an if statement including 'mc' but it just ends with eg 'mcdonnell' in the line only.

I tried to add the code but I kept getting an error saying indent with 4 spaces which I did but it still didn't like it so not sure what I was missing there.

You could do something like this

names = [['bob', 'smith', 'green'],
['jon', 'mc', 'donnell', 'red'],
['fred', 'thomas', 'blue'],
['jim', 'mc', 'donald', 'orange']]

for name in names:
    if name[1] == 'mc':
         concat_middle = name.pop(1) + name.pop(1)
         name.insert(1, concat_middle)       

Assuming you always want to concatenate the next immediate word after 'mc' to it. You can try this using iter and taking advantage of next .

a=[['bob', 'smith', 'green'],
['jon', 'mc', 'donnell', 'red'],
['fred', 'thomas', 'blue'],
['jim', 'mc', 'donald', 'orange']]

[[i+next(it) if i=='mc' else i for i in it] for it in map(iter,a)]

Output:

[['bob', 'smith', 'green'],
 ['jon', 'mcdonnell', 'red'],
 ['fred', 'thomas', 'blue'],
 ['jim', 'mcdonald', 'orange']]

I'm assuming this is the behaviour you desire: for a list of lists, you want to merge the 2nd and 3rd element of a list with 4 elements?

A verbose solution:

for i, array in enumerate(array_of_arrays):
    if len(array) == 4:
        middle = array[1] + array[2]
        array_of_arrays[i] = [array[0], middle, array[3]]

Note I use Python's enumerate method, which returns an array as a pair of index and the respective element.

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