简体   繁体   English

编写循环级联和 if 语句的 Pythonic 方式?

[英]Pythonic way to write cascading of loops and if statements?

Maybe this is a super dumb question but I was wondering what is the pythonic way of write this conditions:也许这是一个超级愚蠢的问题,但我想知道编写此条件的 Pythonic 方式是什么:

custom_field_labels = ['value1', 'value2']

def whatever(label):
    if label not in custom_field_labels:
        custom_field_labels.append(label)
    else:
        invalid_name = True

        while invalid_name:
            label += "_"
            if label not in custom_field_labels:
                custom_field_labels.append(label)
                invalid_name = False

whatever('value1')
whatever('value3')
print(custom_field_labels) # ['value1', 'value2', 'value1_', 'value3']

I've read about that recursion is a bad idea in python.我读过关于递归在python中是个坏主意。 Is that true?真的吗? If yes, what are the other options?如果是,其他选择是什么?

You just need one while loop.你只需要一个while循环。

while label in custom_field_labels:
    label += "_"
custom_field_labels.append(label)

If label isn't in the list, the loop will never be entered so you'll append the original label;如果label不在列表中,则永远不会进入循环,因此您将附加原始标签; this is essentially the same as the first if .这与第一个if基本相同。

I also recommend against the pattern我也建议反对这种模式

while boolean_variable:
    # do stuff
    if <some condition>:
        boolean_variable = False

Either test the condition itself in the while condition, or use:while条件中测试条件本身,或使用:

while True:
    # do stuff
    if <some condition>:
        break;

I would like to append "_" into a string while it exists inside custom_field_labels.我想将“_”附加到一个字符串中,而它存在于 custom_field_labels 中。

Then do exactly that?那么到底要不要这样做?

def whatever(label):
    while label in custom_field_labels:
        label += "_"
    custom_field_labels.append(label)

No idea why you're asking about recursion.不知道你为什么要问递归。

Rather than store the almost-the-same labels directly, you can use a Counter object, and reconstruct the labels as needed.您可以使用Counter对象,并根据需要重建标签,而不是直接存储几乎相同的标签。

>>> from collections import Counter
>>> c = Counter(["value1", "value2"])
>>> c['value1'] += 1
>>> c['value3'] += 1
>>> c
Counter({'value1': 2, 'value2': 1, 'value3': 1})
>>> [x+"_"*i for x, n in c.items() for i in range(n)]
['value1', 'value1_', 'value2', 'value3']

(It would be nice if there were an add method so that c.add(x) was equivalent to c[x] += 1 . Oh, well.) (如果有一个add方法让c.add(x)等价于c[x] += 1就好了。哦,好吧。)

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

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