问题描述:
Can someone explain the code please?
def my_func(st):
operations = (str.lower, str.upper)
return ''.join(operations[i%2](x) for i, x in enumerate(st))
I am getting the desired output.
but I am unaware of the 3rd line in the code
解决方案 1:[1]
I imagine the tricky part is operations[i%2](x)
.
This is a trick/hack to select between two functions, but it’s really not readable/explicit and shouldn’t be used in real life.
i%2
returns 1
if i
is odd and 0
if i
is even. Thus for each letter in st
that is enumerated as x
/i
for the value/position (with enumerate
). You code selects between str.lower
and str.upper
by indexing the tuple operations
with 0
/1
depending on the value of i
.
Then it joins all letters in a single string (with str.join
).
A better approach could be to use a ternary:
def my_func(st):
return ''.join(x.upper() if i%2 else x.lower()
for i, x in enumerate(st))
Or itertools.cycle
, which is a bit similar to the original logic but more explicit IMO:
from itertools import cycle
def my_func(st):
c = cycle((str.lower, str.upper))
return ''.join(next(c)(x) for x in st)
解决方案 2:[2]
Enumerate is used to iterate over the characters of the input string along with their indices and returns pairs of (index, character). Then, alternately applies str. lower and str. upper to each character based on its index (operations[i%2] means for each index that is even ), and then joins the results into a single string
参考链接:
Copyright Notice: This article follows StackOverflow’s copyright notice requirements and is licensed under CC BY-SA 3.0.
Article Source: StackOverflow
[1] mozway
[2] Muqri Hafiy