【问题标题】:How To Create A New List of Tuple From One List如何从一个列表创建一个新的元组列表
【发布时间】:2021-01-31 08:46:52
【问题描述】:
sampleList = ['CustomerA', 'Yes', 'No', 'No', 'CustomerB', 'No', 'No', 'No', 'CustomerC', 'Yes', 'Yes', 'No']

Preferred Output : [('CustomerA', 'Yes', 'No', 'No'), ('CustomerB', 'No', 'No', 'No'), ('CustomerC', 'Yes', 'Yes', 'No')]

我想从一个列表创建一个列表元组。

【问题讨论】:

标签: python-3.x list tuples


【解决方案1】:

试试这个。

sampleList = [
    'CustomerA', 'Yes', 'No', 'No', 
    'CustomerB', 'No', 'No', 'No', 
    'CustomerC', 'Yes', 'Yes', 'No'
]
preferredOutput = [
    tuple(sampleList[n : n + 4]) 
    for n in range(0, len(sampleList), 4)
]
print(preferredOutput)

# OUTPUT (IN PRETTY FORM)
# 
# [
#     ('CustomerA', 'Yes', 'No', 'No'), 
#     ('CustomerB', 'No', 'No', 'No'), 
#     ('CustomerC', 'Yes', 'Yes', 'No')
# ]

【讨论】:

    【解决方案2】:

    你可以使用列表推导output=[tuple(sampleList[4*i:4*i+4]) for i in range(3)]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-27
      • 2020-10-15
      相关资源
      最近更新 更多