Python questions! (Correct the questions below)

Asked 2 years ago, Updated 2 years ago, 37 views

a[] = {1,3,2, 4,5,9, 7,6,1, 2,3,4, 5,6,7}

for(int = 0; i<3;i++){

if(a[i]=='1') { print("number 1")}

if(a[i]=='2') { print("number 2")}

if(a[i]=='3') { print("number 3")}

if(a[i]=='4') { print("number 4")}

if(a[i]=='5') { print("number 5")}

if(a[i]=='6') { print("number 6")}

if(a[i]=='7') { print("number 7")}

if(a[i]=='8') { print("number 8")}

if(a[i]=='9') { print("number 9")}

Result value

= Number 1 Number 3 Number 2

It's a chord that comes out like this.

If you press the switch, 1, 3, 2, and then 4, 5, 9... Press the switch one more time, and then press the next three (4,5,9) one more time (7,6,1,)... I want to make a loop that repeats over and over again.

(print("Number /") will turn on the LED to match the number of temporary figures)

python raspberry-pi

2022-09-22 18:37

1 Answers

Python has a zip function that allows you to bind each element of the tuple.

If you use this, you can do it as follows.

In [1]: a = (1,3,2, 4,5,9, 7,6,1, 2,3,4, 5,6,7,)

In [2]: [a[i::3] for i in range(3)]                                            
Out[2]: [(1, 4, 7, 2, 5), (3, 5, 6, 3, 6), (2, 9, 1, 4, 7)]

In [3]: list(zip(*[a[i::3] for i in range(3)]))                                
Out[3]: [(1, 3, 2), (4, 5, 9), (7, 6, 1), (2, 3, 4), (5, 6, 7)]

In [4]: for v1, v2, v3 in list(zip(*[a[i::3] for i in range(3)])): 
    ...:     ...:     print(v1, v2, v3) 
    ...:                                                                        
1 3 2
4 5 9
7 6 1
2 3 4
5 6 7


2022-09-22 18:37

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.