سؤال

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. 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:

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]:

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

Explanation

dataList is, e.g, (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)

What we want to get is a flattened dataList, i.e, [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[1] is a list with two elements: [u'$14,995', u'31,750']

[dataList[0]] + dataList[1] will concatenate these two lists and we'll get the flattened dataList.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top