考虑这两个数据结构:
var_a = [['apple','fruit','1'],['banana', 'fruit', '2'],['orange', 'fruit', '3']]
文本文件内容:
'1', '20,000', 'USA'
'2', '45,000', 'Russia'
'3', '56,000', 'China'
我想使用列表推导,它会给我一个输出如下:
'Apple', '1', '20,000', 'USA'
'Banana', '2', '45,000', 'Russia'
'Orange', '3', '56,000', 'China'
到目前为止我尝试过的代码是:
import json
file = open(name, 'r') #read in rows of data from text file
file_rows = file.read()
file_rows = file_rows.split('\n')
for x_file in file_rows:
x_file2 = x_file.split(',')
my_text_file = open(text_file_path, 'r')
var_a = my_text_file.read() #read in list of lists from text file
the_list = json.loads(var_a.replace("'", '"'))
if any(x_file2[0] == x[2] for x in the_list) == True:
print xfile2[0], x
我仍然有点像我追求的那样。有人能告诉我如何修改列表理解以实现所需的输出吗?
由于
答案 0 :(得分:1)
以下是使用itertools
:
import itertools
with open('/tmp/my_text_file.txt') as f:
new_list = [list(itertools.chain(item[1][:1], item[0].strip().replace("'", "").split(", "))) for item in zip(f.readlines(), var_a)]
# new_list = [['apple', '1', '20,000', 'USA'], ['banana', '2', '45,000', 'Russia'], ['orange', '3', '56,000', 'China']]