简体   繁体   English

如何通过将列表元素与 Python 中的字符串进行比较来找到列表元素的索引?

[英]How to find the index of a list element by comparing it to a string in Python?

Suppose if I had a list that contains some files, like so:假设我有一个包含一些文件的列表,如下所示:

file_list = ['folder\\text.txt', 'folder\\data.csv', 'folder\\picture.png']

And also declared a string:并且还声明了一个字符串:

file = 'text.txt'  #Did not include 'folder\\', intentionally.

How can I grab the index of the file_list by using the 'file' variable?如何使用“文件”变量获取 file_list 的索引?

I have tried the following:我尝试了以下方法:

index = file_list.index(file)
filename = file_list[index]
print(filename)

However, I am getting this result:但是,我得到了这个结果:

ValueError: 'text.txt' is not in list

I've understood why my solution failed but is there an efficient solution for grabbing the index by using the string variable?我已经理解为什么我的解决方案失败了,但是是否有一个有效的解决方案可以通过使用字符串变量来获取索引?

This will help you:)这将帮助你:)

file_list = ['folder\\text.txt', 'folder\\data.csv', 'folder\\picture.png']
file = 'data.csv'
flag = True
for i in range(len(file_list)):
    if(file_list[i].find(file)!=-1):
        print("file found at {} position in the list".format(i))
        flag = False
        break
if flag:
    print ("File not found :(")

OUTPUT: OUTPUT:

file found at 0 position in the list

given you don't want to use os module (as you said in the comment), just implement a basic basename func based on split.鉴于您不想使用os模块(正如您在评论中所说),只需实现一个基于 split 的基本基本basename func。

then, you can use a simple comprehension to create a matching list with just the filenames, and look for the index in it.然后,您可以使用简单的理解来创建一个仅包含文件名的匹配列表,并在其中查找索引。

def basename(path):
  return path.split('\\')[-1]

file_list = ['folder\\text.txt', 'folder\\data.csv', 'folder\\picture.png']
file = 'text.txt'

file_basename_list = [basename(f) for f in file_list]

index = file_basename_list.index(file)

filename = file_list[index]
print(filename)

Output: Output:

folder\text.txt

You should check each element of file_list to findout the index of file :您应该检查file_list的每个元素以找出file的索引:

def find_index(file, file_list):
    for idx, file_name in enumerate(file_list):
        if file in file_name:
            print(f"idx:{idx}, file_name:{file_name}")
            return idx


if __name__ == '__main__':
    file_list = ['folder\\text.txt', 'folder\\data.csv', 'folder\\picture.png']
    file = 'text.txt'
    idx = find_index(file, file_list)
    if idx:
        print(file_list[idx])
    else:
        print(f"Couldn't find idx of {file} ")

Output: Output:

idx:0, file_name:folder\text.txt
folder\text.txt

The straightforward way to do this would be:直接的方法是:

file_list = ['folder\\text.txt', 'folder\\data.csv', 'folder\\picture.png']
search_file = 'text.txt'
base_path = "folder\\"

def find_file(file_list, search_file, base_path):
    for idx, file in enumerate(file_list):
        if file == base_path+search_file:
            return idx
    return "File Not Found"

print(find_file(file_list, search_file, base_path))

If you want to add the base_path dynamically then use:如果要动态添加base_path ,请使用:

import os.path 

path = 'folder\\'
base_path = os.path.basename(path)

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

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