Reputation:
Maybe this is a super dumb question but I was wondering what is the pythonic way of write this conditions:
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. Is that true? If yes, what are the other options?
Upvotes: 1
Views: 71
Reputation: 531055
Rather than store the almost-the-same labels directly, you can use a Counter
object, and reconstruct the labels as needed.
>>> 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.)
Upvotes: 0
Reputation: 780861
You just need one while
loop.
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; this is essentially the same as the first 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 True:
# do stuff
if <some condition>:
break;
Upvotes: 5
Reputation: 27588
I would like to append "_" into a string while it exists inside 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.
Upvotes: 0