Skip to content Skip to sidebar Skip to footer

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'] li

Solution 1:

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

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

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

Solution 2:

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.

Solution 3:

>>> [x foryin [list1, list2] forxin 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']

Post a Comment for "Modifying List Elements Based On Key Word Of The Element"