Search code examples
pythontuplesnested-lists

How to drop elements in 'y' position of a nested list of tuples?


I have a nested list of tuples:

[[('complacency', 0.0001833514688884038),
  ('complexity', 0.00020885722118234196),
  ('system', 0.00030831926569582427),
  ('accidents', 0.0003527060442832197),
  ('major', 0.0003577792651629483),
  ('accident', 0.000556904280447189),
  ('Safety', 0.0005632664174249453),
  ('issue', 0.000604949484895331),
  ('risk', 0.000655457410972149),
  ('complex', 0.0007215989124478362)],
 [('situation', 0.00029301996954456724),
  ('awareness', 0.0003444184039291439),
  ('people', 0.00201798567882153),
  ('loss', 0.002527094648295153),
  ('constructs', 0.002921195578537488),
  ('complacency', 0.003951273394687846),
  ('human', 0.004937009924663634),
  ('world', 0.004937009924663634),
  ('Dekker', 0.004963844372504768),
  ('representational', 0.006297840866917582)]]

I want to drop the y element from every tuple (the numbers), but I need to be able to preserve the nested structure of the list.


Solution

  • You can use list comprehension:

    lst = [[('complacency', 0.0001833514688884038), ('complexity', 0.00020885722118234196), ('system', 0.00030831926569582427), ('accidents', 0.0003527060442832197), ('major', 0.0003577792651629483), ('accident', 0.000556904280447189), ('Safety', 0.0005632664174249453), ('issue', 0.000604949484895331), ('risk', 0.000655457410972149), ('complex', 0.0007215989124478362)], [('situation', 0.00029301996954456724), ('awareness', 0.0003444184039291439), ('people', 0.00201798567882153), ('loss', 0.002527094648295153), ('constructs', 0.002921195578537488), ('complacency', 0.003951273394687846), ('human', 0.004937009924663634), ('world', 0.004937009924663634), ('Dekker', 0.004963844372504768), ('representational', 0.006297840866917582)]]
    
    output = [[x for x, _ in sublst] for sublst in lst]
    
    print(output)
    # [['complacency', 'complexity', 'system', 'accidents', 'major', 'accident', 'Safety', 'issue', 'risk', 'complex'],
    #  ['situation', 'awareness', 'p eple', 'loss', 'constructs', 'complacency', 'human', 'world', 'Dekker', 'representational']]