Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
基于Python中第一个列表的ID从第二个列表获取值_Python_Loops - Fatal编程技术网

基于Python中第一个列表的ID从第二个列表获取值

基于Python中第一个列表的ID从第二个列表获取值,python,loops,Python,Loops,我是Python的初学者,有一个我读过的文件,其中有一个Market\u ID字段。在循环浏览此文件(列表)时,我需要访问第二个文件(Market\u ID,Market\u name)中的Market\u名称 我最好从哪里开始?如果必要的话,我可以提供更多关于程序正在做什么的细节 文件(列表)如下所示: File1: Cust_ID, Market_ID, Cust_Name, IsNew File2: Market_ID, Market_Name 我的主循环在File1上。我需要能够从

我是Python的初学者,有一个我读过的文件,其中有一个Market\u ID字段。在循环浏览此文件(列表)时,我需要访问第二个文件(Market\u ID,Market\u name)中的Market\u名称

我最好从哪里开始?如果必要的话,我可以提供更多关于程序正在做什么的细节

文件(列表)如下所示:

File1:  Cust_ID, Market_ID, Cust_Name, IsNew
File2:  Market_ID, Market_Name

我的主循环在File1上。我需要能够从文件2中访问Market_名称,以便能够将其放置在我根据文件1中的数据创建的新文件中。希望有帮助。

嗯,你能提供更多细节吗

当你说文件(列表)时,你的意思是你已经创建了一个包含第一个文件中所需的所有数据的列表吗?第二个文件呢

如果它们都是列表,则类似的操作将起作用:

for market_id in flie1_list:
    for pair in file2_list:
        if pair[0] == market_id: 
            market_name = pair[1]
            break
    <keep doing whatever it is you need to do in first loop>
对于flie1\u列表中的市场标识:
对于文件2_列表中的对:
如果对[0]==市场id:
市场名称=对[1]
打破

注意-我也是一个初学者,这是我在这个网站上的第一个答案。放松点;)

如果文件不太大(几兆字节),您可以使用Market_ID作为键将每个项目存储在dict()中

这看起来像是数据库中的数据存储—如果您熟悉关系数据库及其使用,可以将每个文件插入单独的表中,然后执行查询。Python在其标准库中有一个到sqlite的接口


为了快速解决这个问题,我建议使用dicts。

我不熟悉python,但从概念上讲,您可能需要将第二个文件读入第一个文件,然后在字典中查找id以获得关联的名称。或者,如果ID是数字的,密度或多或少,您可以将它们读入一个常规数组


如果文件不太大(几兆字节),可以使用Market_ID作为键将每个项目存储在dict()中

这看起来像是数据库中的数据存储—如果您熟悉 关系数据库及其使用您可以将每个文件插入 分离表,然后执行查询。Python有一个到的接口 sqlite在其标准库中

为了快速解决这个问题,我建议使用dicts。 通过--

,,


展示一些数据示例怎么样?只需稍作调整,现在就可以了。感谢@Nicoretti和其他人的投入。
file2 = open("/path/to/file2", "r")
market_names = {}
for line in file2:
  fields = line.split(",")
  market_names[int(fields[0])] = fields[1]
file2.close()

file1 = open("/path/to/file1", "r")
for line in file1:
  fields = line.split(",")
  market_name = market_names[int(fields[1])]
  # do what ever you want with the Market_Name associated with
  # the Market_ID contained in this line
file1.close()