Py学习  »  FMc  »  全部回复
回复总数  4

如果你想计算事物,考虑使用 Counter . 它们也可以加减,所以你可以做一些事情 这样地:

from collections import Counter

def minSteps(s: str, t: str) -> int:
    cs = Counter(s)
    ct = Counter(t)
    diff = (cs - ct) + (ct - cs)
    return sum(diff.values())
4 年前
回复了 FMc 创建的主题 » 比较python中字典列表中的值

按ID对DICT进行分组,然后合并每组。

from collections import defaultdict

def merge_dicts(dicts):
    grouped = defaultdict(list)
    for d in dicts:
        grouped[d['id']].append(d)

    merged = []
    for ds in grouped.values():
        m = {}
        for d in ds:
            m |= d        # If Python < 3.9 : m = {**m, **d}
        merged.append(m)

    return merged
4 年前
回复了 FMc 创建的主题 » 函数调用期间未调用Python input()

对于代码的当前行为,您得到了很多解释,但没有 关于如何做我认为你想做的事情,有很多实用的建议。你没有 需要来回传递规则函数。你需要最重要的 获取用户输入的工具:while true循环。

def game():
    if not yesno('Do you know the rules'):
        rules()
    print("Ok. Starting game ...")

def rules():
    while True:
        print("The rules of this game are ... BLAH BLAH")
        if yesno('Do you understand'):
            break

def yesno(question):  
    while True:
        yn = input(f'{question}? [yes/no]: ').lower()
        if yn in ('y', 'yes'):
            return True
        elif yn in ('n', 'no'):
            return False
        else:
            print("Invalid input.")

7 年前
回复了 FMc 创建的主题 » python:类内的字典理解[复制]

公认的答案提供了极好的信息,但这里似乎还有一些其他的问题——列表理解和生成器表达式之间的差异。我玩过的演示:

class Foo:

    # A class-level variable.
    X = 10

    # I can use that variable to define another class-level variable.
    Y = sum((X, X))

    # Works in Python 2, but not 3.
    # In Python 3, list comprehensions were given their own scope.
    try:
        Z1 = sum([X for _ in range(3)])
    except NameError:
        Z1 = None

    # Fails in both.
    # Apparently, generator expressions (that's what the entire argument
    # to sum() is) did have their own scope even in Python 2.
    try:
        Z2 = sum(X for _ in range(3))
    except NameError:
        Z2 = None

    # Workaround: put the computation in lambda or def.
    compute_z3 = lambda val: sum(val for _ in range(3))

    # Then use that function.
    Z3 = compute_z3(X)

    # Also worth noting: here I can refer to XS in the for-part of the
    # generator expression (Z4 works), but I cannot refer to XS in the
    # inner-part of the generator expression (Z5 fails).
    XS = [15, 15, 15, 15]
    Z4 = sum(val for val in XS)
    try:
        Z5 = sum(XS[i] for i in range(len(XS)))
    except NameError:
        Z5 = None

print(Foo.Z1, Foo.Z2, Foo.Z3, Foo.Z4, Foo.Z5)