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

时间:2018-11-20 03:44:10

标签: python python-3.x

我从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',...

我该怎么办?

4 个答案:

答案 0 :(得分:5)

您有一个三元组列表:

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

您要将这个列表重构为三个变量:

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

您可以使用列表理解来做到这一点:“通过从k的每个元素中获取第myList个值来建立列表”。看起来像这样:

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

当然,如果元组的长度可变,则会变得更加复杂-但这是基础知识,您可以根据需要使用它们来解决问题。

答案 1 :(得分:2)

您还可以zip()将结果保存在字典中:

>>> 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')]
>>> fields = 'fieldOne', 'fieldTwo', 'fieldThree'
>>> dict(zip(fields, zip(*myList)))
{'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')}

然后,您可以仅引用此词典中的'fieldOne''fieldTwo''fieldThree'键并将其存储在数据库中。

答案 2 :(得分:0)

给出您的数据,这是一个可能的解决方案:

# Initialize each field list
fieldOne = []
fieldTwo = []
fieldThree = []

# fetch each **item** in **myList**, we extract the component corresponding
# append it to the appropriate field
for item in myList:
    fieldOne.append(item[0])
    fieldTwo.append(item[1])
    fieldThree.append(item[2])

答案 3 :(得分:0)

我建议使用以下方式,以便您可以多次使用它。

def create_field(myList):
    fieldOne = [myList[i][0] for i in range(len(myList))]
    fieldTwo = [myList[i][1] for i in range(len(myList))]
    fieldThree = [myList[i][2] for i in range(len(myList))]
    return fieldOne, fieldTwo, fieldThree
create_field(myList)