简体   繁体   English

python多任务可读性

[英]python multiple assignment readability

Simple question - but I cannot seem to find anything via google... 一个简单的问题-但我似乎无法通过Google找到任何东西...

Lets say I have two variables set independently. 可以说我有两个独立设置的变量。 They should have the same value. 它们应该具有相同的值。 Now these two variables find themselves in a new function, ready to be combined. 现在,这两个变量将在一个新函数中找到并准备好组合。

First I want to make sure they are the same. 首先,我要确保它们相同。 And then I want to set a third variable (id) to the value of the two (id_1,id_2) to make the code more clear. 然后,我想将第三个变量(id)设置为两个变量(id_1,id_2)的值,以使代码更清晰。

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

What is the correct 'pythonic' way to do this. 什么是正确的“ pythonic”方法? What is most readable? 最易读的是什么? Or is there a better way to accomplish this (and scale to > 2 initial variables)? 还是有更好的方法来做到这一点(并扩展到> 2个初始变量)? Previously I have used (option #1). 以前我曾经使用过(选项1)。

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

I would do: 我会做:

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

and for multiple values: 对于多个值:

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

I usually keep assert for debugging purposes, hence the try statement. 我通常保持断言用于调试目的,因此使用try语句。

I'd define your other function as taking a list, rather than a bunch of variables you don't really need, then use any to check that they all match. 我将其他函数定义为列表,而不是一堆您不需要的变量,然后使用any来检查它们是否匹配。 You don't need to check every value against every other value, just check the first one against all the others: 您不需要将每个值都与其他值进行比较,只需将第一个值与所有其他值进行比较:

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`

Note that id isn't really a great name for a variable, since it's also the name of a builtin function (which your code will not be able to use, since its name will be shadowed). 请注意, id实际上并不是变量的好名字,因为它也是内置函数的名称(您的代码将被遮盖,因此您的代码将无法使用)。 If your id s represent some specific kind of objects, you might use a name like foo_id to be more explicit about what its purpose is. 如果您的id代表某种特定类型的对象,则可以使用foo_id类的名称来更明确地说明其用途。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM