考虑这两个数据结构:
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
我对我所追求的还有一点不了解。有人能告诉我应该如何修改列表以达到预期的输出吗
谢谢
下面是使用
itertools
理解列表的示例代码:相关问题 更多 >
编程相关推荐