简体   繁体   中英

Is it possible to assign a for statement to a variable in python?

I'm a student in python and have an assignment that requires me to write code without using pandas. I need to assign a print statement to a variable, and I'd like to include a for loop so that it's dynamic.

For now, I've hard-coded the number of print statements, and that's good enough for the assignment, but I'd like to know for future reference if there's some way to put a for loop into a variable.

What I've done (and this works fine since I know how many print statements I need):

x = (
    f"{names[i]} : {percent[i]}% ({votes[i]})"\n
    f"{names[i]} : {percent[i]}% ({votes[i]})"\n
    f"{names[i]} : {percent[i]}% ({votes[i]})"\n
)

print(x)

What I could do so that I don't need to know the end of the range in advance:

for i in range(0,len(candidates)):
    print(f"{names[i]} : {percent[i]}% ({votes[i]})")

This second piece of code works beautifully so long as I don't assign it to a variable. The problem is that I'm required to assign it to a variable.

When I do this:

x = for i in range(0,len(candidates)):
        print(f"{names[i]} : {percent[i]}% ({votes[i]})")

print(x)

I get:

SyntaxError: invalid syntax

pointing to the line saying for i in range(0,len(candidates)):

I assume this means I can't assign a for loop to a variable. Is there a work-around that would let me do it?

Assign an empty container to x before the loop then in the loop, instead of printing, add each string to the container - x will contain multiple strings when the loop finishes. If you look through the documentation you should be able to find a suitable container.

If x is supposed to be a single string: assign an empty string to x before the loop then in the loop add/concatenate to x .

Like aaaakshat said, you can assign the result to a list.

One way to do that would be to create a list from a for-loop generator, and then join each item with a newline, such as below.

x = '\\n'.join([f"{names[i]} : {percent[i]}% ({votes[i]})" for i in range(len(candidates))])

Explanation

What we do is make the list, by cycling through all the numbers between 0 and the length of candidates . This is done by the for i in range(len(candidates)) part.

For each of those, we generate your string ( f"{names[i]} : {percent[i]}% ({votes[i]})" ).

By putting this in square brackets, we tell python to make a list of all of these strings.

Then we put a newline ( '\\n' ) between each item to join the strings in the list ( '\\n'.join ).

Finally, we assign this to the variable x .

I think you are doing Assign the result of a loop to a variable in Python . So that question has many ways to achieve this. But you want to Python: Assign print output to a variable . It seems you are looking for List Comprehensions according to the syntax of your question. This what official Python documentation mentioned about List Comprehensions .

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

This is the format of the List Comprehensions and just forget about the Predicate(Optional) section.

在此处输入图片说明

So your loop should be converted in this way and it will create a List Comprehensions .

在此处输入图片说明

This will work, but when you assign print() statement to the variable it will return None value. Then you have to agreed with @EdWard's answer . His answer also mention how it actually works and how it fits with your question.

And one thing, you don't need to pass the start value to the range() if it starts with 0 , see what doc mentioned about it.

The value of the start parameter (or 0 if the parameter was not supplied)

So you can simply use range(len(candidates)) without passing start value. You can use both ways

>>> # this way ending without new line
>>> x = '\n'.join([f"{names[i]} : {percent[i]}% ({votes[i]})" for i in range(len(candidates))])
>>> x
'a : 1% (7)\nb : 2% (8)\nc : 3% (9)'
>>> print(x)
a : 1% (7)
b : 2% (8)
c : 3% (9)

>>>
>>> # this way ending with new line
>>> x = ''.join([f"{names[i]} : {percent[i]}% ({votes[i]})\n" for i in range(len(candidates))])
>>> x
'a : 1% (7)\nb : 2% (8)\nc : 3% (9)\n'
>>> print(x)
a : 1% (7)
b : 2% (8)
c : 3% (9)


>>>

You can't use a for loop in that manner, however you can use something known as List comprehension which will allow you to assign the value to a variable.

In your case you would create a variable to store the values like so and print it out with new line separators:

x = [(f"{names[i]} : {percent[i]}% ({votes[i]})") for i in range(len(candidates))]

print(*x, sep="\n")

# using print syntax
# '*' creates a space between the list items, 'sep' defines the separator

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM