Advanced Python list comprehension

后端 未结 6 2391
北海茫月
北海茫月 2021-02-20 14:02

Given two lists:

chars = [\'ab\', \'bc\', \'ca\']
words = [\'abc\', \'bca\', \'dac\', \'dbc\', \'cba\']

how can you use list comprehensions to

相关标签:
6条回答
  • 2021-02-20 14:37

    Using zip:

    [w for w in words if all([a in c for a, c in zip(w, chars)])]
    

    or using enumerate:

    [w for w in words if not [w for i, c in enumerate(chars) if w[i] not in c]]
    
    0 讨论(0)
  • 2021-02-20 14:39

    A more simple approach:

    yourlist = [ w for w in words for ch in chars if w.startswith(ch) ]
    
    0 讨论(0)
  • 2021-02-20 14:40
    [w for w in words if all([w[i] in chars[i] for i in range(len(w))])]
    
    0 讨论(0)
  • 2021-02-20 14:45

    This works, using index:

    [words[chars.index(char)] for char in chars if char in words[chars.index(char)]]
    

    Am I missing something?

    0 讨论(0)
  • 2021-02-20 14:45

    Why so complex? This works as well:

    [words[x] for x in range(len(chars)) if chars[x] in words[x]]
    
    0 讨论(0)
  • 2021-02-20 14:52
    >>> [word for word in words if all(l in chars[i] for i, l in enumerate(word))]
    ['abc', 'bca']
    
    0 讨论(0)
提交回复
热议问题