Suppose I have the below list in 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:
['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.
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.
you can use itertools.cycle
and itertools.accumulate
to get a generator that yields the desired indexes.
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))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.