Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
83 views
in Technique[技术] by (71.8m points)

python - How do I convert my output to list format?

I am trying to convert my output as:

[5130, 5415, 5700, 5985, 6270, 6555, 6840, 7125, 7410, 7695, 7980]

but I only get:

5130
5415
5700
5985
6270
6555
6840
7125
7410
7695
7980

I have no clue how to convert it. I am inputing the number 15.

my code:

x = int(input("Enter your number here: "))

def inrange(x):
  for i in range(5000,8000):
    if i % x ==0 and i % (x +4)==0:
      print(i)
inrange(x)

This is the question: Create a program that has a function that takes one integer argument. The function will print a list of all values between 5000 and 8000 that is divisible by (1) the integer argument, and (2) the argument + 4.

question from:https://stackoverflow.com/questions/65908389/how-do-i-convert-my-output-to-list-format

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you wish your function to return a list with your items instead of printing them, try:

x = int(input("Enter your number here: "))

    def inrange(x):
      results = []
      for i in range(5000,8000):
        if i % x ==0 and i % (x +4)==0:
          results.append(i)
      return results
inrange(x)

Edit:

This attempt was modifying your code so it works. The simplest way as mentioned will be:

return [i for i in range(5000,8000) if i % x == 0 and i % (x + 4) == 0]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...