【问题标题】:How to find specific index by its content如何通过其内容找到特定的索引
【发布时间】:2021-07-21 10:58:30
【问题描述】:
wordlist = open(r'C:\Users\islam\Desktop\10k most passwords.txt')

for words in wordlist:
    line = (words.split())  
    for count, ele in enumerate(wordlist, 1):
        x=(([count, ele]))
        print(x)

输出:

[9994, 'hugohugo\n']

[9995, '八十\n']

[9996, '爱普生\n']

[9997, '福音派\n']

[9998, 'eeeee1\n']

[9999, 'eyphed']

如何通过输入索引 0 的内容找到索引 0,例如输入 9995,输出为:

[9995, '八十\n']

【问题讨论】:

    标签: python list indexing


    【解决方案1】:

    这是一种方法:

    with open('path/to/file') as file:
        data = file.readlines()
    
    
    while True:
        try:
            user_input = int(input('Enter index:'))
            if user_input < 1:
                raise ValueError
            print(data[user_input - 1].strip())
        except (ValueError, IndexError):
            print('Invalid index value')
    

    我想说的很简单,因为如果您按 readlines 拆分它已经是一个列表并且可以使用索引(从 1 减去 1 以“开始”索引)访问,其余包含错误处理的代码是为了方便用户.

    仅用于从“硬编码”索引中获取值:

    with open('path/to/file') as file:
        data = file.readlines()
    
    index = 5    
    print(data[index - 1])
    

    【讨论】:

    • 感谢它的工作! , 我希望有一天能像你一样,我花了 1 个小时思考如何做到这一点,我只能说精致
    • 当我删除输入并在 user_input 的值中添加数字时出现问题使单词无限循环
    • @Islamhamdi 好吧,是的,它不使用input() 这样做的原因是因为输入会停止一切并等待用户输入某些内容,如果您想在代码中指定索引,只需执行@ 987654324@ (.strip() 不是必需的,它只是删除了尾随的换行符)(put_index_here 只需将实际整数放入:print(data[5 - 1]))(-1 到从 1 开始的“开始”索引)(以及其中的代码案例可能就像 3 行)
    • 我更新了代码以包含我在其他评论中提到的示例
    • 好的,但是如果您在代码中输入索引,那么就没有太多需要尝试所有的东西,除了东西,您可以像我在回答中所做的那样,在如果你想在代码中指定索引,我在底部添加了代码,你可以继续尝试,除非你真的需要
    【解决方案2】:

    你可以试试这个:

    list.index(element, start, end)
    
    element - the element to be searched
    start (optional) - start searching from this index
    end (optional) - search the element up to this index
    

    在列表的地方你写你的列表名称。 我认为这可能会有所帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-31
      • 2014-12-13
      • 2011-04-27
      • 1970-01-01
      • 2016-01-18
      • 1970-01-01
      相关资源
      最近更新 更多