如果你想避开for循环,我认为你需要的是:
有关更多信息,请查看:
enumerate
,和
join
sep = ' - '
a = 'apple - banana - lemon - melon'
b = a.split(sep) #Turns the string into a list of âitems
b = enumerate(b) #Turns the items list into [(item_index, item), ...]
c = f"{b[1]}.{b[0]}" #Formats item.index how you were
d = sep.join(c) #puts them all together in a neat little string separated by âsepâ
e = d[:len(d)-len(sep)]
print(e)
但这一步一步的简单分解。下面是
b
,
c
,和
d
sep = ' - '
a = 'apple - banana - lemon - melon'
b = enumerate(a.split(sep))
c = sep.join(f"{b[1]}.{b[0]}")
d = c[:len(c)-len(sep)]
print(d)
不过,如果我没弄错的话
list comprehension
编辑:
功劳归于@Patrick Haugh。对于列表理解。
d = sep.join('{}.{}'.format(i, s) for i,s in enumerate(a.split(sep), start=1)
我也在你的基础上修正了我的,因为我加入了str和int,我的想法是他试图不使用for循环。