如何获取列表中的项目索引?

时间:2018-08-19 14:04:33

标签: python python-3.x list for-loop indexing

我有两个清单。

第一个列表包含语言,并包含约30000个项目。

['es','de', 'ita', ....]

第二个列表包含大约二十种语言代码,如下所示:

['eng', 'ar', 'fr', 'ch', 'jp', 'ita' .... ]

我想做的是搜索并查看第1本书是否与代码19有关(1是第一本书的索引),如果找到,请打印第二个列表中的代码索引

import csv

book_language_list = []
with open('language_table_for_search.csv', 'r') as rf:
    reader = csv.reader(rf, delimiter=',')
    for row in reader:
      book_language_list.append(row[2])


book_language_distinc = []
with open('language_codes.csv', 'r') as rf:
    reader = csv.reader(rf, delimiter=',')
    for row in reader:
      book_language_distinc.append(row[1])


for i in range(0, len(book_language_list)):    
    if any(book_language_list[i] in s for s in book_language_distinc):
        # print the book id=i has language=(found language index)

3 个答案:

答案 0 :(得分:4)

一种方法是使用文档中的索引函数:

  

此方法返回找到的对象的索引,否则引发   指示找不到值的异常。

赞:

books = ['es', 'de', 'ita', 'eng']
codes = ['eng', 'ar', 'fr', 'ch', 'jp', 'ita']

for book in books:
    try:
        ii = codes.index(book)
        print(book, ii)
    except ValueError:
        pass

输出:

ita 5
eng 0

如果按书有多种语言,并且每本书都由一个列表表示,则可以这样操作:

books = [['es'], ['de'], ['ita', 'ch'], ['eng']]
codes = {code: ii for ii, code in enumerate(['eng', 'ar', 'fr', 'ch', 'jp', 'ita'])}

for book in books:
    book_codes = [(lang, codes[lang]) for lang in book if lang in codes]
    if book_codes:
        print(book_codes)

输出:

[('ita', 5), ('ch', 3)]
[('eng', 0)]

该行:

codes = {code: ii for ii, code in enumerate(['eng', 'ar', 'fr', 'ch', 'jp', 'ita'])}

创建一个字典,其中是语言代码,而是列表中的索引。最后,

book_codes = [(lang, codes[lang]) for lang in book if lang in codes]

获取代码中的书籍语言,如果列表不为空,则打印结果。

答案 1 :(得分:2)

简单解决方案: 使用set()

set & set返回两个集合的交集。

示例:

books = ['es', 'de', 'ita', 'eng']
codes = ['eng', 'ar', 'fr', 'ch', 'jp', 'ita']
for r in set(books)&set(codes):
    print(r, codes.index(r))

返回:

eng 0
ita 5

答案 2 :(得分:0)

使用enumerate解决了以下问题:

for i in range(0, len(book_language_list)):    
    print("book {} has language {}={}".format(i, book_language_list[i], [j for j, s in enumerate(book_language_distinc) if book_language_list[i] in s]))

输出:

book 27279 has language 'us'=[5]