[英]Change every nth item in a list
For, example if I wanted to make every second uppercase and lowercase like 例如,如果我想使第二个大写和小写像
original_list = ['FisH', 'Dog', 'cow', 'piG']
desired_list = ['fish', 'DOG', 'cow', 'PIG']
my way to go about it was to make a separate lists for upper and lower words and then join them some how but I know this is a bad/ way to do it: 我的解决方法是为上下两个单词分别创建一个列表,然后以某种方式将它们加入,但是我知道这是一个不好的方法:
list1 = []
list2 = []
for i in orginal_list[0::2]:
i = i.lower()
list1.append(i)
for i in orginal_list[1::2]:
i = i.upper()
list2.append(i)
With enumerate()
function and modulo division by 2 (to detect an even positions): 使用
enumerate()
函数并以2除以模 (检测偶数位置):
original_list = ['FisH', 'Dog', 'cow', 'piG']
result = [w.lower() if not i%2 else w.upper() for i,w in enumerate(original_list)]
print(result)
The output: 输出:
['fish', 'DOG', 'cow', 'PIG']
Similar to your own, but assigning the slices right back. 与您自己的相似,但立即分配切片。
mylist[::2] = map(str.lower, mylist[::2])
mylist[1::2] = map(str.upper, mylist[1::2])
Demo: 演示:
>>> mylist= ['FisH', 'Dog', 'cow', 'piG']
>>> mylist[::2] = map(str.lower, mylist[::2])
>>> mylist[1::2] = map(str.upper, mylist[1::2])
>>> mylist
['fish', 'DOG', 'cow', 'PIG']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.