【问题标题】:How to find the direct link between the list elements?如何找到列表元素之间的直接链接?
【发布时间】:2021-03-09 07:26:58
【问题描述】:

我有一个元素之间可能的连接列表,例如:

J&K - Punjab
J&K - Himachal Pradesh
Himachal Pradesh - Punjab
Himachal Pradesh - Haryana
Himachal Pradesh - Uttranchal
Punjab - Haryana
Punjab - Rajasthan
Punjab - UP
Haryana - Uttranchal
Haryana - Delhi
Haryana - Rajasthan
Haryana - Chhattisgarh
Haryana - Gujrat
Uttranchal - UP
Rajasthan - Gujrat
Rajasthan - Madhya Pradesh
Rajasthan - UP
Rajasthan - Delhi
UP - Delhi
UP - Madhya Pradesh
UP - West Bengal
UP - Bihar
UP - Assam
Chhattisgarh - Madhya Pradesh
Chhattisgarh - Maharashtra
Chhattisgarh - Tamil Nadu
Chhattisgarh - Orissa
Chhattisgarh - Jharkhand
Gujrat - Madhya Pradesh
Gujrat - Maharashtra
Madhya Pradesh - Maharashtra
West Bengal - Assam
West Bengal - Sikkim
West Bengal - Bihar
West Bengal - Jharkhand
West Bengal - Orissa
Bihar - Sikkim
Bihar - Jharkhan
Assam - Arunachal Pradesh
Assam - Nagaland
Assam - Manipur
Assam - Mizoram
Assam - Tripura
Assam - Meghalaya
Jharkhan - Orissa
Maharashtra - Goa
Maharashtra - Karnataka
Maharashtra - Telangana
Orissa - Karnataka 
Orissa - Andhra Pradesh
Goa - Karnataka
Karnataka - Telangana
Karnataka - Tamil Nadu
Karnataka - Kerala
Telangana - Andhra Pradesh
Tamil Nadu - Kerala
Tamil Nadu - Andhra Pradesh

所以我想找到州之间的直接联系。例如,如果我说我想找到Rajasthan 可能的链接,那么它应该为我们提供所有可能的直接链接的输出,如下所示:

Rajasthan - Gujrat
Rajasthan - Madhya Pradesh
Rajasthan - UP
Rajasthan - Delhi
Haryana - Rajasthan
Punjab - Rajasthan

我想不出一个可能的逻辑,有人可以帮忙吗?

【问题讨论】:

  • 您可以制作一个字典,在其中为每个州列出该州的可能链接列表。所以在你的例子中看起来像{"Rajashtan": ["Gujrat", "Madhya Pradesh", "UP", "Delhi"]。因此,当您搜索时,您可以检查该状态的字典键,或检查状态所在的每个值,或两者兼而有之。
  • “告诉我如何解决这个编码问题”是off-topic for Stack Overflow。您需要发送honest attempt at the solution,然后就您的实施提出具体问题。

标签: python list search


【解决方案1】:

这基本上是@Cristian 在评论中所说的,但你可以这样做:

from collections import defaultdict
# all_text is the text containing the plain string of the list you wrote above, with each line separated by \n
all_text = np.array(all_text.split('\n'))

connection = defaultdict(list)
for entry in all_text:
    entry = entry.split(' - ')
    connection[entry[0]].append(entry[1])
    connection[entry[1]].append(entry[0])

print(connection['Rajasthan'])

这将返回['Punjab', 'Haryana', 'Gujrat', 'Madhya Pradesh', 'UP', 'Delhi']

【讨论】:

  • 你能举个all_text的例子吗?
  • all_text = '''J&K - Punjab ...所有其他行... Tamil Nadu - Andhra Pradesh'''(必须用新行分隔)
【解决方案2】:

你可以像这样做一个简单的 for 循环:

connections_list = [
    'J&K - Punjab',
    'J&K - Himachal Pradesh']

for x in connections_list:
    _temp = x.split("-")
    for y in connections_list:
        if _temp[0] in y:
            print(y)

【讨论】:

    猜你喜欢
    • 2016-06-13
    • 1970-01-01
    • 1970-01-01
    • 2021-06-14
    • 2016-04-11
    • 2018-03-12
    • 2017-05-24
    • 1970-01-01
    • 2015-11-12
    相关资源
    最近更新 更多