Python 3.x 如何将一对列表拆分为一对列表?
我有这样一份清单:Python 3.x 如何将一对列表拆分为一对列表?,python-3.x,Python 3.x,我有这样一份清单: l = [('coronavirus', 96), ('virus', 30), ('rna', 26), ('human', 25), ('respiratory', 23)] 我想像这样分成两部分: l1 = ['coronavirus', 'virus', 'rna', 'human', 'respiratory'] l2 = [96, 30, 26, 25, 23] 我尝试了以下代码,但返回了AttributeError(“tuple”对象没有属性“split”)
l = [('coronavirus', 96), ('virus', 30), ('rna', 26), ('human', 25), ('respiratory', 23)]
我想像这样分成两部分:
l1 = ['coronavirus', 'virus', 'rna', 'human', 'respiratory']
l2 = [96, 30, 26, 25, 23]
我尝试了以下代码,但返回了AttributeError(“tuple”对象没有属性“split”)
如何才能成功拆分列表?
非常感谢 您的元素已经是元组了,似乎您正在尝试对字符串进行操作 你可以简单地做
l1, l2 = zip(*l)
如果希望l1
和l2
成为列表(而不是元组),可以使用map(list,zip(*l))
或[列表(零件)对应于zip中的零件(*l)]
作为参考,请参阅。特别是“zip()与*运算符一起可用于解压缩列表”。
l1, l2 = zip(*l)