有条件地将列表列表与文本行合并

2024-05-15 09:55:45 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑这两个数据结构:

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

我对我所追求的还有一点不了解。有人能告诉我应该如何修改列表以达到预期的输出吗

谢谢


Tags: oftextinjson列表readvaropen
1条回答
网友
1楼 · 发布于 2024-05-15 09:55:45

下面是使用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']]

相关问题 更多 >