Unable to display list

Asked 2 years ago, Updated 2 years ago, 243 views

I want to calculate and display the value multiplied by 2 in the list I created, so I wrote the following code, but I can't do it well.What should I do?

 numbers = [1,3,5,7]
for n in numbers*2:
    print(n)

Run Results

1
3
5
7
1
3
5
7

python

2022-09-30 22:01

1 Answers

There are several possible solutions as shown in the code below.
numbers*2 doubles the array itself, so review it.
numbers=[1,3,5,7], so numbers*2 is calculated from the image of [1,3,5,7][1,3,5,7][1,3,5,7,1,3,5,7].

ご As you asked, I have modified it to print while changing lines for each element.
末You must install the numpy package to run the last Ex.

 numbers = [1,3,5,7]

print("Twice the value of each item in the array by looping while adding the index for the number of 1.numbers")
for i in range (len(number)) :
    print(number[i]*2)

print("Take out 2.numbers one at a time and display double the value")
numbers = [1,3,5,7]
for n in numbers:
    print(n*2)

print("3. Multiply all items in the array by 2 and apply the print function to the array element in map")
list(map(print, [n*2 for n in numbers]))

print("Use Ex.numpy to expand 2x np.array and print in batches with newline character delimited")
import numpy as np
ar=np.array(number)
print(*(ar*2), sep="\n")


2022-09-30 22:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.