dyao
dyao

Reputation: 1011

List Comprehension to For Loop

I know its better/easier to do certain things in a list comprehension, but not all languages have such a useful tool.

So I wonder how they do it.

Take this example:

>>> mylist=[[1,2,3],[3,4,5]]
>>> rows = ['\t'.join([str(v) for v in row]) for row in mylist]

>>> print(rows)

['1\t2\t3', '3\t4\t5']

What is the equivalent in a for loop (even though would be much more work)?

Upvotes: 1

Views: 95

Answers (4)

Martin Evans
Martin Evans

Reputation: 46759

Your list comprehension can be split out into the following:

rows = []

for row in mylist:
    temp = []

    for v in row:
        temp.append(str(v))

    rows.append("\t".join(temp))

print rows

Giving the same output:

['1\t2\t3', '3\t4\t5']

Upvotes: 1

The6thSense
The6thSense

Reputation: 8335

mylist=[[1,2,3],[3,4,5]]
rows=[]   
for row in mylist:
    rows.append("\t".join(map(str,row)))
rows
['1\t2\t3', '3\t4\t5']

Without map and join:

mylist = [[1, 2, 3], [3, 4, 5]]
rows = []
for row in mylist:
   s=""
   for v in row:
       s+=str(v)+"\t"
   rows.append(s.rstrip())
rows
['1\t2\t3', '3\t4\t5']

Upvotes: 4

HichamDz38
HichamDz38

Reputation: 104

if you want to print every element(list) in a single line and all element in the internal list separately by space.

for i in mylist:
    for j in i:
        print j,
    print

1 2 3

4 5 6

Upvotes: 2

franciscod
franciscod

Reputation: 1000

This one does it without using join, map, or list comprehensions: just for-loops.

Note how concise is the code when you use these very expresive tools, in comparison with the classic double iteration:

mylist = [[1, 2, 3], [3, 4, 5]]

rows = []
for row in mylist:
    r = ''
    prefix = ''
    for v in row:
        r += prefix + str(v)
        prefix = '\t'
    rows.append(r)

Upvotes: 2

Related Questions