简体   繁体   中英

Deleting elements in a list based on a spectific tuple value

So I want to have a list with elements in it being added and replaced based on a specific tuple value when being traversed through.

I tried some basic logic to delete the previous element in order to 'replace' it with the new one, however the old element seems to not be erased.

 a = [['a','1','f'],['a','2','f'],['a','3','t'],['b','4','f'],['b','5','t'],['c','6','f']]


 z = []
 z.append(a[0])

 for i in range(1, len(a)):
     if str(a[i]).split(',')[2] == 't' and str(a[i]).split(',')[0] == str(a[i-1]).split(',')[0]:
         del z[i]
         z.append(a[i])
     elif a[i] not in z:
             z.append(a[i])

So here I have a list 'a' with some tuple values in the list. Some of the values (a,b,c) may repeat, and have a corresponding value (f or t). What I want is to add these tuples into 'z' if not already existing, and then if I find one that is existing and has corresponding value 't', I'd get rid of the old one and replace it with this.

So the final output of the z should be:

 ['a','3','t'], ['b','5','t'],['c','6','f']

We traverse through 'a', see that ['a','1','f'] initially is not in 'z'. We add it and continue traversing. Then we see the 3rd element has ['a','3','t'], So we delete the original one with 'f' and replace with the 't'. We do this for 'b' as well, and for 'c', there is no 't' value corresponding to it so we leave it be.

Thank you for your help.

You can do this fairly trivially with a dict:

>>> a = [['a','f'],['a','f'],['a','t'],['b','f'],['b','t'],['c','f']]
>>> [*dict(a).items()]
[('a', 't'), ('b', 't'), ('c', 'f')]

In older versions of Python (<= 3.6), do the same using a collections.OrderedDict .

Added from comments: The dict() constructor takes (among other options) an iterator of tuples as argument and parses them in the order presented into dictionary items. Dictionary keys must all be unique, so this would parse your first three elements all into key my_dict['a'] , leaving the value equal to the last key 'a' that was read, or my_dict['a'] = 't' . Same with 'b' and 'c' . Then you unpack the values that remain in the dictionary into a list. This should work provided it's the last item for each key present in your input list that you want to keep.

Based on updated input list from the question and @wim answer, I added some comments:

a = [['a','1','f'],['a','2','f'],['a','3','t'],['b','4','f'],['b','5','t'],['c','6','f']]

# assume that a is *NOT* sorted:
l = sorted(a, key=lambda k: (k[0], k[2]=='t'))
# now list `l` contains sorted elements from `a` and elements containing `t` are in the "back"

# we will feed this sorted list do `dict()` as [key, value] pairs where key is first element in array
# and value is whole item
print([*dict([i[0], i] for i in l).values()])

Prints:

[['a', '3', 't'], ['b', '5', 't'], ['c', '6', 'f']]

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