python多重赋值可读性

2024-05-15 02:24:16 发布

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

简单的问题-但我似乎找不到任何通过谷歌。。。你知道吗

假设我有两个独立设置的变量。 它们应该具有相同的值。现在这两个变量在一个新的函数中找到了它们自己,准备合并。你知道吗

首先我要确定它们是一样的。 然后我想将第三个变量(id)设置为这两个变量的值(id\u1,id\u2),以使代码更清晰。你知道吗

id_1=5
id_2=5

# ensure id_1==id_2
assert id_1 == id_2

id=id_1 # option 1
id=id_2 # option 2
id=id_1=id_2 # option 3

正确的“Python”方法是什么。 什么是最可读的?或者有没有更好的方法来实现这一点(并扩展到>;2个初始变量)?以前我使用过(选项1)。你知道吗


Tags: 方法函数代码gtid选项assertoption
3条回答

我将您的另一个函数定义为获取一个列表,而不是一堆您并不真正需要的变量,然后使用any检查它们是否都匹配。您不需要将每个值与其他值进行比较,只需将第一个值与所有其他值进行比较:

id, *rest = list_of_values # this is Python 3 syntax, on earlier versions use something
                           # like `id, rest = list_of_values[0], list_of_values[1:]`
assert(all(id == other_id for other_id in rest))

# do stuff here with `id`

请注意,id对于变量来说并不是一个很好的名称,因为它也是一个内置函数的名称(您的代码将无法使用它,因为它的名称将被隐藏)。如果id表示某种特定类型的对象,则可以使用foo_id这样的名称来更明确地说明其用途。你知道吗

def f(*args):
    if args[1:] == args[:-1]: #test all args passed are equal
        id = args[0] #set your 'id' to the first value
    else:
        return None # just as an example
    # do things ...
    return id

>>> f(1,2,3,4)
None
>>> f(1,1,1,1)
1

我会做:

try:
    id = id1 if id1==id2 else int('')
except ValueError as e:
    #fix it or
    raise ValueError('id1 and id2 are different.') from e

对于多个值:

try:
    id = args[0] if len(set(args))==1 else int('')
except ValueError as e:
    #fix it or
    raise ValueError('id1 and id2 are different.') from e

我通常保留assert用于调试,因此使用try语句。你知道吗

相关问题 更多 >

    热门问题