Does anyone know how to convert this List Comprehensions to normal for loop code:
results = ['A' , 'B', 'C' , 'D']
]for i in [results[c:c+2] for c in range(0,len(results)) if c%2 == 0]:
print(*i)
output:
A B
C D
The ] before the for loop is an error.
Converting a comprehension to a loop si pretty straight forward. Write the loops backwards.
for i in [results[c:c+2] for c in range(0,len(results)) if c%2 == 0]
becomes
temp = []
for c in range(0, len(results)):
if c % 2 == 0:
temp.append(results[c:c+2])
for i in temp:
print(*i)
I like this way better:
results = iter(["A", "B", "C", "D"])
for i in zip(results, results):
print(*i)
As already stated, there's an error (a typo, maybe?)
This is how I would do it:
results = ['A', 'B', 'C', 'D']
for index, c in enumerate(results):
if index % 2 == 0:
print(*results[index:index + 2])
Output:
A B
C D
I've used
index
rather than
i
, but it's the same thing.
Thanks.
It was a typo.
Basely I was trying to find some solution to nth index of a list and add a new line.
For example, if my list has hundreds of data, I just wish new line after 2 columns.
So I went to StackOverflow and found this solution, but I'm unfamiliar with list Comprehension.
Thanks for all the help.
(Oct-20-2022, 04:46 AM)rob101 Wrote: [ -> ]As already stated, there's an error (a typo, maybe?)
This is how I would do it:
results = ['A', 'B', 'C', 'D']
for index, c in enumerate(results):
if index % 2 == 0:
print(*results[index:index + 2])
Output:
A B
C D
I've used index
rather than i
, but it's the same thing.
HI rob101,
Is it possible to write it into a text file, instead of print?
(Oct-21-2022, 01:14 PM)jacklee26 Wrote: [ -> ]HI rob101,
Is it possible to write it into a text file, instead of print?
Yes; you simply add a file handler and redirect the
print()
function:
with open('output.txt', 'a') as output:
results = ['A', 'B', 'C', 'D']
for index, c in enumerate(results):
if index % 2 == 0:
print(*results[index:index + 2], file=output)
That will create a file called
output.txt
within the same directory from which the python script is run.
Use range with a step instead of enumerate and modulo.
results = ['A', 'B', 'C', 'D']
for index in range(0, len(results), 2):
print(*results[index:index + 2])
The call is range(stop) or range(start, stop[, step]). If you want to use a step you need to specify the start. All arguments are positional.