生成一个将向lis添加唯一字符的代码

2024-04-25 00:38:13 发布

您现在位置:Python中文网/ 问答频道 /正文

所以下面的代码应该讨论msg中的唯一字符和唯一字符,并制作一个包含两个子列表的列表。例如

crack_the_code('hello there', 'abccd eabfb') 

你应该回来

[['h', 'e', 'l', 'o', 't', 'r'], ['a', 'b', 'c', 'd', 'e', 'f']].

我在下面尝试做的是创建三个列表,然后运行for循环来检查我是否在新列表中(unique),如果不在新列表中,则将其添加到列表中,对unique\u代码也是这样做的。你知道吗

最后把这两张单子放在一起并返回,但当我打印出来时一张也没有。任何帮助都将不胜感激。你知道吗

def crack_the_code(msg, code):
    unique = []
    unique_code = []
    cracked = []
    for i in msg:
        if i not in unique:
            unique.extend(i)
    for item in code:
        if item not in unique_code:
            unique_code.extend(item)
    cracked = unique.append(unique_code)
    return cracked

print(crack_the_code('hello there', 'abcd eabfb'))

Tags: the代码inhello列表forcodemsg
2条回答

您得到None,因为unique.append(unique_code)变异unique,并且不返回修改后的列表,而是None(所有变异输入的函数都应该如此)。你可以做return [unique, unique_code]。你知道吗


在确定了回报率之后,你应该使用更好的算法。每当您检查if i not in unique时,这会线性地检查列表unique中的值i,使其总计O(n^2)。你知道吗

这是使用^{} recipe ^{},它保持原始顺序,是O(n),因为它使用set来跟踪已经看到的字母:

from itertools import filterfalse

def unique_everseen(iterable):
    "List unique elements, preserving order. Remember all elements ever seen."
    # unique_everseen('AAAABBBCCDAABBB')  > A B C D
    seen = set()
    seen_add = seen.add

    for element in filterfalse(seen.__contains__, iterable):
        seen_add(element)
        yield element

def crack_the_code(msg, code):
    return [list(unique_everseen(msg)), list(unique_everseen(code))]

如果您不能使用itertools,您也可以自己编写(可能稍微慢一点):

def unique_everseen(iterable):
    "List unique elements, preserving order. Remember all elements ever seen."
    # unique_everseen('AAAABBBCCDAABBB')  > A B C D
    seen = set()
    seen_add = seen.add

    for element in iterable:
        if element not in seen:
            seen_add(element)
            yield element

如果您不关心顺序,只需使用set

def crack_the_code(msg, code):
    return [list(set(msg)), list(set(code))]

用append交换extend,用extend交换append。我想你把它们的功能搞糊涂了。你知道吗

将元素附加到列表中。 您可以将一个列表扩展到另一个列表。你知道吗

另外,您在第二个for循环中使用了[item],但将[i]添加到列表中。将其更改为[项目],然后以下代码起作用:

def crack_the_code(msg, code):
    unique = []
    unique_code = []
    cracked = []
    for i in msg:
        if i not in unique:
            unique.append(i)

    for item in code:
        if item not in unique_code:
            unique_code.append(item)        

    cracked = unique + unique_code

    return cracked

print(crack_the_code('hello there', 'abcd eabfb'))

相关问题 更多 >