Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - Need to make a list from a function

I want to change the a variable from 1 to 50 and create an array from the results so that I can feed it into a curve.

The variable is outside the function but the variable changes a value in the function, that is what I need to make a list of.

a=1

def test(foo):
    p =a+2
    print(p)

test(foo)

I want to get the p values when I change a from 1 to 50:

[3,4,5,6,7,8,9...]
question from:https://stackoverflow.com/questions/65949487/need-to-make-a-list-from-a-function

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

1 Reply

0 votes
by (71.8m points)

Not sure what you trying to do but if you need a list of numbers with some starting point, you can simply generate them using list comprehension as:

a = 2
x = [i+a for i in range(1, 50)]
print(x)

EDIT: Based on comments from author.

You need to change print to return the generated number. Also, need to add a loop and a list to generate a new number and keep appending the new number to the list.

Note: As said earlier, it is recommended to use Python's supported features like list comprehension as is shown in the original code.

a = 1

def test(i):
    p = a + i
    return p

res = []
for i in range(2, 50):
    res.append(test(i))

print(res)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...