python – 如何用逗号分割包含一组字符串的列表?

我在列表中有一组字符串,我从CSV文件中读取它,它看起来像这样:

myList = ('17.0.1.34', '17.1.182.21', '714'),('203.84.210.248', '27.111.228.3', '10310'),('202.73.40.45', '27.111.228.6', '18106'),...

我想将它存储到一个有三个字段的数据库(Django)中:

fieldOne = '17.0.1.34', '203.84.210.248','202.73.40.45', ....
fieldTwo = '17.1.182.21', '27.111.228.3', '27.111.228.6', ...
fieldThree = '714', '10310', '18106',...

我该怎么办?

最佳答案 你有一个3元组的列表:

myList = [
    (a1, b1, c1),
    (a2, b2, c2),
    (a3, b3, c3),
    ...
]

您想将此列表重构为三个变量:

fieldOne = [a1, a2, a3, ...]
fieldTwo = [b1, b2, b3, ...]
fieldThree = [c1, c2, c3, ...]

您可以使用列表推导来执行此操作:“通过从myList的每个元素中获取第k个值来创建列表”.这看起来像这样:

fieldOne = [i[0] for i in myList]    # k = 0
fieldTwo = [i[1] for i in myList]    # k = 1
fieldThree = [i[2] for i in myList]  # k = 2

当然,如果你的元组长度可变,这会变得更复杂 – 但这些是基础知识,你可以根据需要随意使用它们来解决你的问题.

点赞