0

So me and my buddy are helping each other learn about programming, and we have been coming up with challenges for ourselves. He came up with one where there are 20 switches. We need to write a program that first hits every other switch, and then every third switch, and then every fourth switch and have it output which are on and off.

I have the basic idea in my head about how to proceed but, I'm not entirely sure how to pick out every other/3rd/4th value from the list. I think once I get that small piece figured out the rest should be easy.

Here's the list:

start_list = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

I know I can select each element by doing:

start_list[2]

But then, how do I choose every other element, and then increment it by 1?

4

3 回答 3

2

使用Python 的列表切片表示法

start_list[::2]

切片如[start:stop:step]. [::2]意味着,从头到尾,获取每一个第二个元素。这将返回每隔一个元素。

我相信您可以弄清楚如何获得每第三和第四个值:p。


要更改每个值,您可以执行以下操作:

>>> start_list[::2] = len(start_list[::2])*[1]
>>> start_list
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0]
于 2013-07-08T23:41:00.677 回答
1
>>> start_list = [0] * 20
>>> for i in range(2, len(start_list)):
...     start_list[::i] = [1-x for x in start_list[::i]]
... 
>>> start_list
[0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1]
于 2013-07-09T00:02:56.023 回答
1

每隔一个开关:

mylist[::2]

每三分之一:

mylist[::3]

您也可以分配给它:

mylist=[1,2,3,4]
mylist[::2]=[7,8]
于 2013-07-08T23:36:27.850 回答