简体   繁体   English

在python中展平嵌套字符串列表

[英]Flattening nested string list in python

I have two lists, one is not nested, the other is. 我有两个列表,一个不嵌套,另一个是。

carNames = []
priceAndMileage = []

Data looks like this, combined: 数据看起来像这样,合并:

[(u'2011 Toyota Camry SE V6', [u'$14,995', u'31,750']), (u'2012 Toyota Camry L', [u'$15,993', u'27,381'])]

My code is: 我的代码是:

combinedData = zip(carNames, priceAndMileage)

writer = csv.writer(open("dict.csv", 'r+'))

for dataList in combinedData:
    dataList = [dataList[0]] + [y for x in dataList[1] for y in x]
    writer.writerow(dataList)

I flattened the dataList, however it iterates over EVERY character, instead of just the item. 我展平了dataList,但它遍历每个角色,而不仅仅是项目。 How I can I produce results such as the flatten task does not flatten each character, but just the item sub-list? 如何生成诸如展平任务之类的结果并不会使每个字符变平,而只是展现项目子列表?

And my result is in the csv file: 我的结果是在csv文件中:

2011 Toyota Camry SE V6,$,1,4,",",9,9,5,3,1,",",7,5,0
2012 Toyota Camry L,$,1,5,",",9,9,3,2,7,",",3,8,1

But I need: 但是我需要:

2011 Toyota Camry SE V6, $14,995, 31,750
2012 Toyota Camry L, $15,993, 27,381

To flatten dataList you can concatenate [dataList[0]] and dataList[1] : 要展平dataList您可以连接[dataList[0]]dataList[1]

   for dataList in combinedData:
        dataList = [dataList[0]] + dataList[1]
        writer.writerow(dataList)

Explanation 说明

dataList is, eg, (u'2011 Toyota Camry SE V6', [u'$14,995', u'31,750']) (by the way dataList is not a list , it's a tuple - basically an immutable version of list) dataList是,例如, (u'2011 Toyota Camry SE V6', [u'$14,995', u'31,750']) (顺便说一下dataList不是list ,它是一个tuple - 基本上是列表的不可变版本)

What we want to get is a flattened dataList , ie, [u'2011 Toyota Camry SE V6', u'$14,995', u'31,750'] . 我们想得到的是一个扁平的dataList ,即[u'2011 Toyota Camry SE V6', u'$14,995', u'31,750']

[dataList[0]] is a list with only one element: [u'2011 Toyota Camry SE V6'] [dataList[0]]是一个只有一个元素的列表: [u'2011 Toyota Camry SE V6']

dataList[1] is a list with two elements: [u'$14,995', u'31,750'] dataList[1]是一个包含两个元素的列表: [u'$14,995', u'31,750']

[dataList[0]] + dataList[1] will concatenate these two lists and we'll get the flattened dataList . [dataList[0]] + dataList[1]将连接这两个列表,我们将获得展平的dataList

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM