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

Pythonic编写循环和if语句级联的方法?,python,python-3.x,Python,Python 3.x,也许这是一个超级愚蠢的问题,但我想知道在这种情况下,python的写作方式是什么: 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

也许这是一个超级愚蠢的问题,但我想知道在这种情况下,python的写作方式是什么:

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']
我读过关于递归在python中是个坏主意的文章。这是真的吗?如果是,还有哪些选择


当u存在于自定义_字段_标签中时,我想将它附加到字符串中

那你到底是怎么做的

def whatever(label):
    while label in custom_field_labels:
        label += "_"
    custom_field_labels.append(label)
不知道你为什么要问递归


当u存在于自定义_字段_标签中时,我想将它附加到字符串中

那你到底是怎么做的

def whatever(label):
    while label in custom_field_labels:
        label += "_"
    custom_field_labels.append(label)
不知道你为什么要问递归。

你只需要一个while循环

如果标签不在列表中,循环将永远不会被输入,因此您将附加原始标签;这与第一个if基本相同

我也反对这种模式

while boolean_variable:
    # do stuff
    if <some condition>:
        boolean_variable = False
你只需要一个while循环

如果标签不在列表中,循环将永远不会被输入,因此您将附加原始标签;这与第一个if基本相同

我也反对这种模式

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

与直接存储几乎相同的标签不同,您可以使用计数器对象,并根据需要重新构建标签

>>> 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']

如果有一个add方法,使c.addx等价于c[x]+=1,那就太好了。哦,好吧。

您可以使用计数器对象,根据需要重新构建标签,而不是直接存储几乎相同的标签

>>> 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']

如果有一个add方法,使c.addx等价于c[x]+=1,那就太好了。哦,好吧。

你想实现什么?我想在自定义字段标签中存在的字符串中添加u。如果不存在,只需附加值即可。@boom您可以进一步扩展吗?我还不完全清楚。你想做什么?我想把u添加到一个字符串中,而它存在于自定义的u字段u标签中。如果不存在,只需附加值即可。@boom您可以进一步扩展吗?我还不完全清楚。他问这个问题是因为它可以用递归实现:else:whateverlabel+\他问这个问题是因为它可以用递归实现:else:whateverlabel+_