简体   繁体   English

Python 3:如何在列表中找到一个字符并获取出现次数和位置?

[英]Python 3: How do I find a char in a list and get the number of occurrences and position?

I have a list of letters, I want to see if these letters appear in a list of states. 我有一个字母列表,我想看看这些字母是否出现在状态列表中。 If they do appear, I want to know which letter appears and in which position it appears. 如果确实出现,我想知道出现在哪个字母以及出现在哪个位置。 I want to store it in a variable so I can then compare it to another string. 我想将其存储在变量中,以便随后将其与另一个字符串进行比较。 Below is my example code: 下面是我的示例代码:

    letters = ['a','b','c','d','e']
    states = ['minnesota','new york','florida']
    found_states = [] 

    for letter in letters:
        for state in states:
            if letter in state:
            found_states.append(state)
            #Here instead of appending to a list
            #I want to find the position of each letter
            #without losing the letter itself
            found_letter = {'e':4,'a':8} #desired result for minnesota
            #i want to use found_letter variable to perform additional
            #if statements
    print(found_states)

Try this: 尝试这个:

found_letter = {}
i = 0
for letter in letters:
    i=i+1
    for state in states:
        if letter in state:
            found_states.append(state)
            if letter in found_letter:
                found_letter[letter].append(i)
            else:
                found_letter[letter] = []
                found_letter[letter].append(i)
print(found_states)

You could do something like this to get a list of all indices of the letter 您可以执行以下操作以获取字母的所有索引的列表

state = 'ohio'
letter = 'o'
occurences = [i for i, c in enumerate(state) if c == letter]

You can use list comprehensions ! 您可以使用列表推导

List comprehensions provide a concise way to create lists. 列表理解为创建列表提供了一种简洁的方法。 Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition. 常见的应用是创建新列表,其中每个元素是应用于另一个序列的每个成员或可迭代的某些操作的结果,或者创建满足特定条件的那些元素的子序列。

For every s in states, for every character, check if its present in your letters list. 对于每个s状态,对于每个字符,请检查字母列表中是否存在该字符。 If found, then you can get the index and the character in a list without losing its order! 如果找到,则可以在列表中获取索引和字符而不会丢失其顺序!

>>> [(s,[(index,c) for index,c in enumerate(s) if c in letters]) for s in states]
[('minnesota', [(4, 'e'), (8, 'a')]), ('new york', [(1, 'e')]), ('florida', [(5, 'd'), (6, 'a')])]

If you break down the list comprehension, 如果您分解列表理解,

>>> [s for s in states] 
['minnesota', 'new york', 'florida']

>>> [[c for index,c in enumerate(s)] for s in states] 
[['m', 'i', 'n', 'n', 'e', 's', 'o', 't', 'a'], ['n', 'e', 'w', ' ', 'y', 'o', 'r', 'k'], ['f', 'l', 'o', 'r', 'i', 'd', 'a']]

>>> [[(index,c) for index,c in enumerate(s)] for s in states]
[[(0, 'm'), (1, 'i'), (2, 'n'), (3, 'n'), (4, 'e'), (5, 's'), (6, 'o'), (7, 't'), (8, 'a')], [(0, 'n'), (1, 'e'), (2, 'w'), (3, ' '), (4, 'y'), (5, 'o'), (6, 'r'), (7, 'k')], [(0, 'f'), (1, 'l'), (2, 'o'), (3, 'r'), (4, 'i'), (5, 'd'), (6, 'a')]]

>>> [(s,[(index,c) for index,c in enumerate(s)]) for s in states]
[('minnesota', [(0, 'm'), (1, 'i'), (2, 'n'), (3, 'n'), (4, 'e'), (5, 's'), (6, 'o'), (7, 't'), (8, 'a')]), ('new york', [(0, 'n'), (1, 'e'), (2, 'w'), (3, ' '), (4, 'y'), (5, 'o'), (6, 'r'), (7, 'k')]), ('florida', [(0, 'f'), (1, 'l'), (2, 'o'), (3, 'r'), (4, 'i'), (5, 'd'), (6, 'a')])]

To make access of elements much easier, you can use dict comprehension! 为了使元素的访问更加容易,您可以使用dict理解!

>>>res =  {s:[(index,c) for index,c in enumerate(s) if c in letters] for s in states}
>>> print res
{'minnesota': [(4, 'e'), (8, 'a')], 'new york':[(1, 'e')], 'florida':[(5, 'd'), (6, 'a')]}

So when you wan to access for one state say 'florida' 因此,当您要访问某个州时,请说“佛罗里达”

>>> print res['florida']
[(5, 'd'), (6, 'a')]

Hope it helps! 希望能帮助到你!

You can use a lot of approaches :) 您可以使用很多方法:)

list_of_letters = ['a', 'b', 'c', 'd', 'e', 'n']
states = ['minnesota', 'new york', '

    def search_letters(letters):
        found_states = {}
        for letter in letters:
            for state in states:
                for i, char in enumerate(state):
                    if char in letter:
                        found_states.setdefault(state, []).append(letter + ":" + str(i + 1))
        return found_states

After you use: 使用后:

print search_letters(list_of_letters)

You will receive something like: 您会收到类似以下内容的信息:

{'new york': ['e:2', 'n:1'], 'florida': ['a:7', 'd:6'], 'minnesota': ['a:9', 'e:5', 'n:3', 'n:4']}

So you will receive something like you described in the description of this issue. 因此,您将收到类似于此问题说明中所述的内容。 Of course you can sort the lists of a particular dictionary key, if you want. 当然,您可以根据需要对特定字典键的列表进行排序。

暂无
暂无

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

相关问题 我如何让 python 在列表中找到不同的元素及其在其中的出现次数 - How do i make python find differing elements in a list and their number of occurrences within it 我如何获得位置而不是在python中交换清单编号 - How do i get position instead of swapping in list number in python Python如何查找列表中是否有数字,而不是列表的最后一个数字? - Python How do I find if an number is in a list but is not last number of the list? 如何计算列表列表中某个位置的特定元素的出现次数? - How do I count occurrences of a specific element in a position in a list of lists? Python 正则表达式如何找到匹配的(子)字符串出现次数? - Python regex how do I find matching number of occurrences of a (sub)string? 在Python中查找“-”登录列表组的出现次数 - Find number of occurrences of groups of '-' sign in list in Python 使用 Python 查找字符串中列表的出现次数 - Find number of occurrences of a list in a string using Python 如何获得熊猫数据框中单词(子字符串)列表的出现次数? - How do I get the number of occurrences of a list of words (substrings) in a pandas dataframe? 如何使用变量在 Python 的列表中查找元素的 position? - How do I use a variable to find the position of an element in a list in Python? 如何在 python 中找到列表的排序位置/索引? - How do I find the sorted position/index of a list in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM