【问题标题】:find unique one-to-one relationship in two lists在两个列表中找到唯一的一对一关系
【发布时间】:2018-06-18 13:00:58
【问题描述】:

我是 python 新手,我目前有一个文本文件,我将其分成两列。我正在文本文件中寻找独特的一对一关系来确定新购房者:

主文件

1234 地址,比利·乔尔

乔·马丁,45 岁,其他地址

63 OtherOther Address, Joe Martin

比利乔尔,1234 地址

我正在寻找独特的一对一关系(1234 Address 和 Billy Joel)

当前步骤/目标:

  1. 根据','将文本文件分成两个列表

想写这样的东西(我知道这是非常可怕的布局,但我被困在如何实现它):

addressListing= text file that is read

leftLst = addressListing.split(",", 1)[0]
rightLst = addressListing.split(".", 1) [1]    

for (x, y) in (leftLst, rightLst):
        if x in rightLst and y in leftLst:
             return x + y
        else:
             pass

文本文件不整洁,一侧只有地址,另一侧只有名称。

【问题讨论】:

  • 输出应该是什么?
  • 您有办法确定某事物是名称还是地址?一旦存在,集合和/或字典就是此类问题的良好数据结构。

标签: python list unique


【解决方案1】:
dict1 = {}
dict2 = {}

for line in content:
    line = line.split(",")
    if len(line) == 2:
        left = line[0].strip()
        right = line[1].strip()

        dict1[left] = right
        dict2[right] = left

for k, v in dict1.items():
    if v in dict2 and dict2[v] == k:
        print("Match found: " + k + ", " + v)

【讨论】:

    【解决方案2】:

    您没有使用足够的数据结构来解决这个问题。首先,当存储在文件中的项目意味着有关系时,请考虑使用database

    虽然,如果您只需要一次性解析文件,那么使用 dict 应该就足够了,而且足够高效。

    代码

    def find_one_to_one(d):
        for k, v in d.items():
            if v in d and d[v] == k:
                return k, v
        else:
            return None
    
    with open('test_file.txt') as file:
        d = {left.strip(): right.strip() for left, right in [row.split(',') for row in file]}
        print(find_one_to_one(d))
    

    测试文件内容

    1234 Address , Billy Joel
    Joe Martin, 45 Other Address
    63 OtherOther Address, Joe Martin
    Billy Joel, 1234 Address
    

    输出

    ('1234 Address', 'Billy Joel')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-23
      • 2023-03-19
      相关资源
      最近更新 更多