简体   繁体   中英

Modifying list elements based on key word of the element

I have many lists which I want to do some operations on some specific elements. So if I have something like:

list1 = ['list1_itemA', 'list1_itemB', 'list1_itemC', 'list1_itemD']
list2 = ['list2_itemA', 'list2_itemC','list2_itemB']

What interest me is item 'itemC' wherever it occurs in all lists and I need to isolate an element which contain itemC for next manipulations on it. I thought about sorting the lists in such a way that itemC occupies the first index which would be achieved by list[0] method.

But in my case itemA, itemB, itemC and itemD are biological species names and I dont know how to force list element occupy the first index (that would be an element with certain string eg 'cow' in my analysis or 'itemC' here). Is this possible with Python?

You can extract items containing "itemC" without ordering, or worrying how many there are, with a "generator expression":

itemCs = []
for lst in (list1, list2):
    itemCs.extend(item for item in lst if "itemC" in item)

This gives itemCs == ['list1_itemC', 'list2_itemC'] .

If you're trying to save the lists with a specific string contained in the text, you can use:

parse_lists = [ list1, list2, list3 ]
matching_lists = []
search_str = "itemC"
for thisList in parse_list:
    if any( search_str in item for item in thisList ):
        matching_lists.append( thisList )

This has an advantage that you don't need to hard-code your list name in all your list item strings, which I'm assuming you're doing now.

Also interesting to note is that changing elements of matching_lists changes the original (referenced) lists as well. You can see this and this for clarity.

>>> [x for y in [list1, list2] for x in y if "itemC" in x]  
['list1_itemC', 'list2_itemC']

or

>>> [x for y in [list1, list2] for x in y if any(search_term in x for search_term in ["itemC"])]  
['list1_itemC', 'list2_itemC']

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