Home > Net >  Python - list of tuples, what conditions should I use to make it work as excepted
Python - list of tuples, what conditions should I use to make it work as excepted

Time:04-07

I have a list of tuples:

lst = [
    ("Tom", "Failed"),
    ("Tom", "Success"),
    ("Kas", "Success"),
    ("Kas", "Success"),
    ("Al", "Warning"),
    ("Al", "Success",
    ("Pel", "Failed"),
    ("Pel", "Failed") 
]

I don't want duplicates so I use set():

set_lst = set(lst)

I get:

{
  ('Al', 'Success'),
  ('Al', 'Warning'),
  ('Kas', 'Success'),
  ('Tom', 'Failed'),
  ('Tom', 'Success'),
  ('Pel', 'Failed')
}

I messed up completely conditions and gave up:

for x, y in set_lst:
    if len({g for _, g in set_lst}) > 1:
        y = "Success"
        print(x, y)
    elif len({g for _, g in set_lst}) <= 1:
        if y == "Failed":
            print(x, y)

I don't know how should I go about it in actuall code.

I treat Warning and Success (if same person) as Success; Failed and Success (if same person) also as Success; Failed as Failed.

If I have:

('Tom', 'Failed') and ('Tom', 'Success') -> Tom Success

('Al', 'Success') and ('Al', 'Warning') -> Al Success

I except:

Al Success
Kas Success
Tom Success
Pel Failed

List of tuples may change.

CodePudding user response:

Try:

lst = [
    ("Tom", "Failed"),
    ("Tom", "Success"),
    ("Kas", "Success"),
    ("Kas", "Success"),
    ("Al", "Warning"),
    ("Al", "Success"),
    ("Pel", "Failed"),
    ("Pel", "Failed"),
]

out = {}
for name, status in lst:
    if name not in out or out[name] != "Success":
        out[name] = status

out = list(out.items())
print(out)

Prints:

[('Tom', 'Success'), ('Kas', 'Success'), ('Al', 'Success'), ('Pel', 'Failed')]
  • Related