简体   繁体   中英

How can I check the format of every n consecutive elements in a list

For example say I have a list of 20 elements and I want to check that every 4 consecutive elements follow a pattern. Consider the following:

list = ["start1", "1/2". "3/4", "end1"]

I want to make sure every 4th element starting from list[0] contains "start" and that every 4th element starting from list[1] and list[2] contain a "/". If not I'd like to input a placeholder " " for example:

I would like list2:

list2 = ["start1", "1/2", "end1"]

To become:

list3 = ["start1", "1/2", " ", "end1"]

Since you're not posting any attempt, I'm not going to give you any full solution, but one hint that you might find useful:

for i in range(0,len(list),3):
    print(list[i])

This code will iterate through every fourth element in your list. Perhaps from here you can think about how to do the check you want and how to perform the inputs you wanted. (Watch out though if you are increasing the length of the list while iterating through it, you may want to manipulate the iteration variable as well).

Of course, there are countless other ways of approaching this task.

it looks like you're trying to move items within a list.

This answer should help you

Move an item inside a list?

So it seems like you'll have to use

insert() and pop()

to deliver what you need.

For the algorithm itself, modulo will be useful since we know that:

if index % 4 == 0 AND contains "start"
  if i + 1 AND i + 2 contains "/"

Cheers!

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM