Python list of tuples, need to unpack and clean up

前端 未结 5 1958
一个人的身影
一个人的身影 2021-01-06 20:24

Assume you have a list such as

x = [(\'Edgar\',), (\'Robert\',)]

What would be the most efficient way to get to just the strings \'Edgar\

5条回答
  •  自闭症患者
    2021-01-06 20:59

    This is pretty straightforward with a list comprehension:

    x = [('Edgar',), ('Robert',)]
    y = [s for t in x for s in t]
    

    This does the same thing as list(itertools.chain.from_iterable(x)) and is equivalent in behavior to the following code:

    y = []
    for t in x:
        for s in t:
            y.append(s)
    

提交回复
热议问题