我有一个像这样的列表
lis = [('a', [('happy:units:1', 'cloud:1'), ('sad:units:1', 'rain:2'), 'rating:3']),]
import csv
with open('Yo456!.csv', 'wb') as out:
csv_out = csv.writer(out, delimiter=',')
csv_out.writerow(['id', 'happy:units', 'cloud', 'sad:units', 'rain', 'rating'])
for row in lis:
csv_out.writerow(row)
但是我得到了OutPut
答案 0 :(得分:0)
编写一个函数来从数据中提取值。
def flatten_row(row):
"""
Transform a row in my weird format into a flat tuple of values.
>>> ('a', [('happy:units:1', 'cloud:1'), ('sad:units:1', 'rain:2'), 'rating:3'])
('a', '1', '1', '1', '2', '3')
"""
pass # YOUR CODE HERE
将您的功能用于名利和利润
for row in lis:
csv_out.writerow(flatten_row(row))
答案 1 :(得分:0)
您可以使用以下代码展平行并在行上进行迭代,以获得所需格式的CSV。假设您的数据始终采用给定格式。
lis = [('a', [('happy:units:1', 'cloud:1'), ('sad:units:1', 'rain:2'), 'rating:3']),]
return_list = list()
# For the sake of simplicity, Im taking the first element of the given list
for item in lis[0]:
# Check if the item is a list
if type(item) is list:
for it in item:
# Iterate over the list item to flatten
if type(it) is tuple:
for x in it:
return_list.append(x[x.rfind(':')+1:])
else:
return_list.append(it[it.rfind(':')+1:])
else:
# If it is not a list then simply append the value
return_list.append(item)
print(return_list)
答案 2 :(得分:0)
你应该看看@jagadeesh mn,因为它看起来更具普遍性。我的答案非常依赖于不可扩展的定位。但是,我发布了一个快速而脏的代码来压扁。
test=[('bba', [('happy:units:1', 'cloud:1'), ('sad:units:1', 'rain:2'), 'rating:3']),('bcc', [('happy:units:2', 'cloud:2'), ('sad:units:1', 'rain:3'), 'rating:5'])]
col_id=[];
col_rating=[];
col_happy=[];
col_cloud=[];
col_sad=[];
col_rain=[];
for row in test:
col_id.append(row[0])
for j,row2 in enumerate(row[1]):
if(j==2):
col_rating.append(row2[row2.rfind(':')+1:])
if(j==0):
for k,row3 in enumerate(row2):
if(k==0):
col_happy.append(row3[row3.rfind(':')+1:])
if(k==1):
col_cloud.append(row3[row3.rfind(':')+1:])
if(j==1):
for k,row3 in enumerate(row2):
if(k==0):
col_sad.append(row3[row3.rfind(':')+1:])
if(k==1):
col_rain.append(row3[row3.rfind(':')+1:])
final_list = list(zip(col_id,col_rating,col_happy,col_cloud,col_sad,col_rain))
答案 3 :(得分:-1)
不易出错的解决方案:
li = [('a', [('happy:units:1', 'cloud:1'), ('sad:units:1', 'rain:2'), 'rating:3']),]
li = list(li[0])
li = [li[0]] + li[1]
def flatten_row(inp_lst):
ou = []
for x in inp_lst:
if isinstance(x, basestring):
ou.append(x)
else:
ou += list(x)
return ou
def get_values(inp_lst):
ou = []
for el in inp_lst:
pos = el.rfind(":") + 1
ou.append(el[pos:])
return ou
with open(output_file, "wb") as f:
writer = csv.writer(f)
writer.writerows([['id', 'happy:units', 'cloud', 'sad:units', 'rain', 'rating'],
get_values(flatten_row(li))])
答案 4 :(得分:-1)
只要输入列表与您提到的模式完好无损,下面的代码就可以了。我已将这些项目放在列表中,您可以按照您希望的方式将它们转换为csv。尝试一下。
lis = [('a', [('happy:units:1', 'cloud:1'), ('sad:units:1', 'rain:2'), 'rating:3']),]
res = list()
for i in xrange(0,len(lis[len(lis)-1])):
if len(lis[0][i]) > 0:
for j in xrange(0,len(lis[0][i])):
if len(lis[0][i][j]) >= 1 and type(lis[0][i][j]) == tuple:
for x in xrange(0,len(lis[0][i][j])):
res.append(lis[0][i][j][x])
else:
res.append(lis[0][i][j])
csv = list()
csv.append(res[0])
for i in xrange(1,len(res)):
csv.append(res[i][:-2]+'='+res[i][len(res[i])-1:])
print("Output: {}".format(csv))
OutPut:
['a', 'happy:units=1', 'cloud=1', 'sad:units=1', 'rain=2', 'rating=3']