将非括号列表项写入CSV单元格

huangapple go评论50阅读模式
英文:

Writing non-bracketed list items to CSV cell

问题

所以我有3个列表,所有3个列表都包含相同数量的项:

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
list3 = [['list_value'], 'string_value', ['another_list_value', 'yet_another_list_value']]

然而,对于list3,我想将字符串值写入CSV单元格,而不是列表。例如:

这样:another_list_value, yet_another_list_value
而不是:['another_list_value', 'yet_another_list_value']

如何最好地做到这一点?我猜想需要使用循环和isinstance检查?

英文:

So I have 3 lists and all 3 contain the same amount of items:

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
list3 = [['list_value'], 'string_value', ['another_list_value', 'yet_another_list_value']]

However for list3, I want to write the string value and not the list to the CSV cell. For example:

This: another_list_value, yet_another_list_value
Instead of: ['another_list_value', 'yet_another_list_value']

What's the best way to do that? I'm guessing a loop and an isinstance check?

答案1

得分: 1

使用join()方法创建逗号分隔的字符串。

csvfile.writerow(i.join(', ') if isinstance(i, list) else i for i in list3)
英文:

Use join() to create a comma-delimited string.

csvfile.writerow(i.join(', ') if isinstance(i, list) else i for i in list3)

huangapple
  • 本文由 发表于 2023年6月16日 01:53:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76484317.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定