也许这是一个超级愚蠢的问题,但我想知道编写此条件的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']
我已经读到递归在python中是一个坏主意。这是真的吗?如果是,还有什么其他选择?
你只需要一个while
循环。
while label in custom_field_labels:
label += "_"
custom_field_labels.append(label)
如果label
不在列表中,则永远不会进入循环,因此您将附加原始标签;这与第一个if
基本相同。
我也建议不要使用这种模式
while boolean_variable:
# do stuff
if <some condition>:
boolean_variable = False
在while
条件下测试条件本身,或使用:
while True:
# do stuff
if <some condition>:
break;
我想将
"_"附加到字符串中,而它存在于custom_field_labels中。
然后就这样做呢?
def whatever(label):
while label in custom_field_labels:
label += "_"
custom_field_labels.append(label)
不知道你为什么要问递归。
您可以使用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']
(如果有一个add
方法,这样c.add(x)
就好了,等同于c[x] += 1
。哦,好吧。