[英]Print alternate 3rd and 4th items of a list in python
Suppose I have the below list in python: myList = ['a','b','c','d','e','f','g','h','i',1,2,3] 假设我在python中具有以下列表:myList = ['a','b','c','d','e','f','g','h','i',1, 2,3]
Now, i basically want a function which will take the list and a enter code here
range as input and print below as the output: 现在,我基本上想要一个将列表和一个enter code here
作为输入并在下面输出作为输出的函数:
['c','g',1] ['c','g',1]
def alternate_num(l,r):
if r >=3 :
if r <= len(myList):
myResult = l[0:r]
first_loc = myResult.index(myResult[2])
second_loc = myResult.index(myResult[6])
newList = list(myResult[first_loc:second_loc + 1:4])
len_list = len(myResult)
print(newList)
newList.append(myResult[i] for i in first_loc)
print(newList)
else:
print("The range provided is greater than the length of the list")
else:
print("Please provide a range greater than 3")
eg suppose i have given a range input as 10, in that case it will take first the 3rd element from the list, then next,it should pick up the alternate 4th element and then it should the next 3rd element and so on. 例如,假设我给定一个范围输入为10,在这种情况下,它将首先从列表中获取第3个元素,然后是下一个,它应该获取替代的第4个元素,然后应该获取下一个第3个元素,依此类推。
so, in this example, my third element is c, hence it is picked up, then it iterates through the list and pick the alternate fourth element ie g and then it picked the alternate 3rd element which is 1. 因此,在此示例中,我的第三个元素是c,因此被选中,然后遍历列表并选择另一个第四个元素g,然后选择了另一个第三个元素1。
you can use itertools.cycle
and itertools.accumulate
to get a generator that yields the desired indexes. 您可以使用itertools.cycle
和itertools.accumulate
获得生成所需索引的生成器。
try this: 尝试这个:
myList = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 1, 2, 3]
def alternate_num(l, r):
if r < 3:
print("Please provide a range greater than 3")
return
if r > len(l):
print("The range provided is greater than the length of the list")
return
from itertools import cycle, accumulate
indexes = accumulate(cycle([3, 4]))
new_list = []
for i in indexes:
if i > r:
return new_list
new_list.append(l[i-1])
print(alternate_num(myList, 10))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.