【问题标题】:Export a list of tuples to a csv in Python [closed]将元组列表导出到 Python 中的 csv [关闭]
【发布时间】:2020-07-13 14:53:27
【问题描述】:

我有一个元组列表:

fruits = [
   ('apple', [('red', 0.25), ('green', 0.21), ('brown', 0.16)]), 
   ('grapes', [('green', 0.88), ('red', 0.76), ('black', 0.59)])
]

每个元组包含 3 种颜色的水果和 3 个分数,我希望水果的名称与颜色和分数一起重复三次。

我想将此元组列表导出为以下格式的 csv:

fruit     colour          score
apple      red             0.25
apple      green           0.21
apple      brown           0.16

grapes     green           0.88
grapes     red             0.76
grapes     black           0.59

谁能帮我用 Python 做这件事

【问题讨论】:

  • 您是否尝试过任何不起作用的方法?

标签: python python-3.x list loops tuples


【解决方案1】:

可能有一些库可以帮助你解决这个问题,但纯 Python 的方式是

fruits = [('apple', [('red', 0.25), ('green', 0.21), ('brown', 0.16)]), ('grapes', [('green', 0.88), ('red', 0.76), ('black', 0.59)])]

lines = ["fruit, color, score"] # list of lines in the output file (hardcode headers)

# loop through every type of fruit
# enumerate will give the key (i) and value (ftype) for every fruit type. for i in range(len(fruits)) would've worked too
for i, ftype in enumerate(fruits):

    # for each fruit type, loop through the colors
    for color in fruits[i][1]:
        # add a line to the CSV for every color
        # if you don't know how format works, look it up. It's really useful
        # the star unpacks the tuple
        lines.append("{}, {}, {}".format(ftype[0], *color))

print("\n".join(lines))

【讨论】:

  • 谢谢。如果可能的话,你能解释一下代码吗
  • 够了吗?
猜你喜欢
  • 2019-11-09
  • 2017-07-20
  • 1970-01-01
  • 1970-01-01
  • 2020-04-01
  • 2015-02-19
  • 1970-01-01
  • 1970-01-01
  • 2019-02-08
相关资源
最近更新 更多