简体   繁体   English

在python中模拟增量(++)运算符

[英]Emulate increment (++) operator in python

My input is a list, say l我的输入是一个列表,比如说l

It can either contain 4 or 5 elements.它可以包含 4 个或 5 个元素。 I want to assign it to 5 variables , say a , b , c , d and e .我想将它分配给 5 个变量,比如abcde

If the list has only 4 elements then the third variable ( c ) should be None .如果列表只有 4 个元素,那么第三个变量 ( c ) 应该是None

If python had an increment (++) operator I could do something like this.如果 python 有一个增量 (++) 运算符,我可以做这样的事情。

l = [4 or 5 string inputs]
i = -1
a = l[i++]
b = l[i++]
c = None
if len(l) > 4:
    c = l[i++]
d = l[i++]
e = l[i++]

I can't seem to find an elegant way to do this apart from writing i+=1 before each assignment.除了在每次分配之前写i+=1之外, i+=1似乎找不到一种优雅的方法来做到这一点。 Is there a simpler pythonic way to do this?有没有更简单的pythonic方法来做到这一点?

You're trying to use a C solution because you're unfamiliar with Python's tools.您正在尝试使用 C 解决方案,因为您不熟悉 Python 的工具。 Using unpacking is much cleaner than trying to emulate ++ :使用解包比尝试模拟++干净得多:

a, b, *c, d, e = l
c = c[0] if c else None

The *c target receives a list of all elements of l that weren't unpacked into the other targets. *c目标接收未解压到其他目标中的l的所有元素的列表。 If this list is nonempty, then c is considered true when coerced to boolean, so c[0] if c else None takes c[0] if there is a c[0] and None otherwise.如果此列表非空,则c在强制为布尔值时被认为是真,因此c[0] if c else None如果存在c[0]则采用c[0] ,否则采用None

The the specific case of this question, list unpacking is the best solution .这个问题的具体情况, list unpacking是最好的解决方案

For other users needing to emulate ++ for other purposes (typically the desire to increment without an explicit i += 1 statement), they can use itertools.count .对于需要出于其他目的模拟++其他用户(通常希望在没有显式i += 1语句的情况下递增),他们可以使用itertools.count This will return an iterator that will increment indefinitely each time it is passed to next() .这将返回一个迭代器,该迭代器每次传递给next()时都会无限增加。

import itertools

i = itertools.count(0)  # start counting at 0
print(next(i))  # 0
print(next(i))  # 1
# ...and so on...

I can't see that you really need to be incrementing at all since you have fixed positions for each variable subject to your c condition.我看不出你真的需要递增,因为你的每个变量都有固定的位置,取决于你的 c 条件。

l = [4 or 5 string inputs]

a = l[0]
b = l[1]

if len(l) > 4:
    c = l[2]
    d = l[3]
    e = l[4]
else:
    c = None
    d = l[2]
    e = l[3]

There is no ++ operator in Python. Python 中没有 ++ 运算符。 A similar question to this was answered here Behaviour of increment and decrement operators in Python与此类似的问题在这里回答了 Python 中自增和自减运算符的行为

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

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