从列表列表中检索和 returns 个字母的函数

Function that retrieves and returns letters from a list of lists

我正在编写一个函数,它需要遍历列表列表,收集所有大写或小写字母,然后 return 一个列表,其中按顺序找到每个字母的 1 个。如果该字母在列表列表中多次出现,该函数只需在第一次看到该字母时报告。

例如,如果列表列表是 [['.', 'M', 'M', 'N', 'N'],['.', '.', '.', '.', 'g'], ['B', 'B', 'B', '.','g']] 然后函数输出应该 return ["M","N","g","B"].

到目前为止,我的代码似乎可以工作,但似乎无法工作。感谢任何帮助

def get_symbols(lot):

    symbols = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

    newlot = []

    for i in lot:
        if i == symbols:
            newlot.append(symbols)
            return newlot
        else:
            return None

您的代码有一些问题。您在错误的地方使用 return,仅在外部列表(而不是子列表中的项目)上循环,并且您将 symbols 附加到 newlot 而不是匹配的项目。

def get_symbols(lot):

    symbols = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' # You should define this OUTSIDE of the function

    newlot = []

    for i in lot: # You are iterating over the outer list only here
        if i == symbols: # == does not check if an item is in a list, use `in` here
            newlot.append(symbols) # You are appending symbols which is the alphabet
            return newlot # This will cause your function to exit as soon as the first iteration is over
        else:
            return None # No need for this

您可以使用双重 for 循环并使用 in 检查字符是否在 symbols 中并且不在 newlot 中:

l = [['.', 'M', 'M', 'N', 'N'],['.', '.', '.', '.', 'g'], ['B', 'B', 'B', '.','g']]
symbols = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

def get_symbols(lot):

    newlot = []

    for sublist in lot:
        for i in sublist:

            if i in symbols and i not in newlot:
                newlot.append(i)

    return newlot

这是您列表的输出:

>>> get_symbols(l)
['M', 'N', 'g', 'B']

以现有代码为基础:

import string

def get_symbols(lot):
    symbols = string.ascii_lowercase + string.ascii_uppercase
    newlot = []

    for sublot in lot:
        for x in sublot:
            if x in symbols and x not in newlot:
                newlot.append(x)

    return newlot

print get_symbols([['.', 'M', 'M', 'N', 'N'],['.', '.', '.', '.', 'g'], ['B', 'B', 'B', '.','g']])

使用 string 让我们的字母更整齐一点。然后我们遍历提供的每个列表(lot 中的每个 sublot),然后对于每个元素 (x),我们检查它是否在我们的所有字母列表和 在我们找到的字母列表中。如果是这种情况,我们将其添加到输出中。

这也可以通过使用 chain, OrderedDict and isalpha 来完成,如下所示

>>> from collections import OrderedDict
>>> from itertools import chain
>>> data = [['.', 'M', 'M', 'N', 'N'],['.', '.', '.', '.', 'g'], ['B', 'B', 'B', '.','g']]
>>> temp = OrderedDict.fromkeys(chain.from_iterable(data))
>>> [x for x in temp if x.isalpha()]
['M', 'N', 'g', 'B']
>>> 

chain.from_iterable 与将所有子列表连接成一个

的目的相同

由于顺序相关,OrderedDict 将达到与 set 相同的目的,即删除重复项并保留添加对象的第一个实例的顺序。 fromkeys class 方法将创建一个具有给定键和相同值的字典,默认情况下是 None,因为我们不关心它,我们的目的是订购者集合

最后 isalpha 会告诉你字符串是否是字母

您还可以查看 unique_everseen 食谱,因为 itertools 是您最好的朋友 我建议将所有这些食谱放在一个随时可用的文件中,它们总是有用的