简体   繁体   English

将列表元素映射到它们的位置(Python)

[英]Mapping list elements into their positions (Python)

I have a list of URLs. 我有一个URL列表。 (We can assume that a given URL is met in the list no more than once.) (我们可以假设列表中的给定URL不超过一次。)

I need a fast way to determine which of two URLs is before in the list. 我需要一种快速的方法来确定列表中的两个URL中的哪一个。

I think, I should create the dict from URL to its position in the list. 我想,我应该从URL创建dict到列表中的位置。

What is the easy way (without writing a for loop with manual increasing of the counter) to map elements of a list into their positions in the list? 什么是简单的方法(没有编写手动增加计数器的for循环)将列表的元素映射到列表中的位置?

The best thing I conceived is: 我设想的最好的事情是:

order = {}
i = 0
for item in list:
    order[item] = i
    i += 1

Now to check if url1 is before url2 , I check order[url1] < order[url2] . 现在检查url1是否在url2之前,我检查order[url1] < order[url2]

Can this code be shortened? 这段代码可以缩短吗?

This creates your order 这会创建您的order

order = {k: v for v, k in enumerate(list)}

Example: 例:

L = list('abc')

Your version: 你的版本:

order1 = {}
i = 0
for item in L:
    order1[item] = i
    i += 1
print(order1)

My version: 我的版本:

order2 = {k: v for v, k in enumerate(L)}
print(order2)

Output: 输出:

{'a': 0, 'b': 1, 'c': 2}
{'a': 0, 'b': 1, 'c': 2}

Better don't use list for your variable name because it is a built-in. 最好不要使用list作为变量名,因为它是内置的。

enumerate provides an iterate that gives you the index and the value for each iteration through your list. enumerate提供了一个迭代,它为您提供列表中每次迭代的索引和值。

If you want to know which comes first for a specific pair of items, you can use the index method on the list: 如果您想知道哪一个是特定项目对的第一个,您可以使用列表中的index方法:

a = ['cat', 'dog', 'fish']

a.index('cat') < a.index('dog') # True
a.index('fish') < a.index('dog') # False

List of URLs: 网址列表:

urls = ['A', 'B', 'C', 'D']

List of indices: 指数清单:

index = range(len(urls))

Create the dict: 创建字典:

order = dict(zip(urls, index))

Test: 测试:

print(order['A'] < order['B'])  # True

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM