简单函数不能修改只包含一个元素的列表

Simple function cannot modify a list containing just one element

我有一个基本函数,可以操作一个二元列表的元组(例如 (["a","b"],["c","d"]))。我还希望它能够处理单元素列表(例如 (["a","b"],["c"]))。

我尝试了两种简单但失败的解决方案。它 看起来 代码行 运行 不连续并导致问题。

函数看起来有点像这样:

def example_func(*args):
    text = ([])
    for a in args:
        text = ([(f"foo:{a[1]}", str(a[0])) for a in args])
    print(text)

example_func(['Hello', "gobbledy"], ['World', "gook"])
# Correct output --> [('foo:gobbledy', 'Hello'), ('foo:gook', 'World')]
example_func(['Hello', "gobbledy"], ['World', " "])
# Correct output --> [('foo:gobbledy', 'Hello'), ('foo: ', 'World')]

但是,如果我删除 gook 它将失败,所以我试图为此例外...

def example_func(*args):
    text = ([])
    for a in args:
        try:            # Just add a try/except condition
            text = ([(f"foo:{a[1]}", str(a[0])) for a in args])
        except Exception:
            text = ([(f"foo: ", str(a[0])) for a in args])
    print(text)

    example_func(['Hello', "gobbledy"], ['World']) # --> Causes index error

这失败了,因为它 运行 陷入索引错误。所以我尝试了...

def example_func(*args):
    text = ([])
    for a in args:
        if len(a) == 1: # If there's just one element, add a 2nd containing whitespace
            a.append(" ")
        text = ([(f"foo:{a[1]}", str(a[0])) for a in args])
    print(text)
example_func(['Hello', "gobbledy"], ['World'])

# This gives an incorrect output:

# [('foo:', 'Hello'), ('foo:', 'World')] --> actual output (fails to print `gobbledy`)
# [('foo:gobbledy', 'Hello'), ('foo:', 'World')] --> desired ouput

所以当我做实验时我试过:

def example_func(*args):
    text = ([])
    for a in args:
        print("a: ", a)
        text = ([(f"foo:{a[1]}", str(a[0])) for a in args])
    print(text)

example_func(['Hello', "gobbledy"], ['World', " "]) # Works
example_func(['Hello', "gobbledy"], ['World']) #FAILS, and doesn't even print the second `a`

由于第二次尝试 运行 for-loop 失败而没有像您预期的那样打印 a: ['World'] ,看起来它 运行 之前的理解和失败打印命令。

当然,没有理解的循环可以完美运行。我确定这是语法或理解上的基本错误,但我真的很困惑。

我认为你想多了:

def example_func(*args):
    text = []
    for a in args:
        if len(a) == 1:
            text.append( ("foo:",a[0]) )
        else:
            text.append( (f"foo:{a[1]}", a[0]) )
    print(text)

example_func(['Hello', "gobbledy"], ['World', " "]) # Works
example_func(['Hello', "gobbledy"], ['World'])

输出:

[('foo:gobbledy', 'Hello'), ('foo: ', 'World')]
[('foo:gobbledy', 'Hello'), ('foo:', 'World')]