1

I am going through automate the boring stuff, diong chapter 6 first practice problems:

tableData = [['apples', 'oranges', 'cherries', 'banana'],
         ['Alice', 'Bob', 'Carol', 'David'],
         ['dogs', 'cats', 'moose', 'goose']]

I would like to tried the following output without using zip function or map cause I am forcing myself to get deeper understanding regarding list manipulation without using those methods.

apples | Alice | dogs

oranges| Bob | cats

cherries | Carol | moose

banana | David | goose

So far I have tried the following:

for i in range(len(tableData[0])):
    print(' '.join(subLst[i] for subLst in tableData))

which does give me intended output, but the range parameter I used feels kinda brutish, so is there any other way I could solve this problem ??

3
  • 2
    If the problem assumes that all sublists have the same length, then I don't see anything wrong with your approach. Commented May 27, 2021 at 22:16
  • Yeah based on the description to that problem we can assume that all sublist will have same length.Again it just to sate my inner curiosity if there is better way to the solve it. Commented May 27, 2021 at 22:31
  • Despite your focus, print(*map(' '.join, zip(*tableData)), sep='\n') is almost irresistible, again assuming common length of sublists. I do want to know why David missed out on plurals though. Commented May 27, 2021 at 22:41

2 Answers 2

1

you can store the each value according to the index in a hash table (dictionary) and then print the result or corresponding index values together

tableData = [['apples', 'oranges', 'cherries', 'banana'],
         ['Alice', 'Bob', 'Carol', 'David'],
         ['dogs', 'cats', 'moose', 'goose']]
         
dic = {}
for sublist in tableData:
    for i, v in enumerate(sublist):
        if i not in dic:
            dic[i]=[v]
        else:
            dic[i].append(v)
            

for k, v in dic.items():
    print(" | ".join(v))

output

apples | Alice | dogs
oranges | Bob | cats
cherries | Carol | moose
banana | David | goose

NOTE: This consider the lenght of sublist is same, if length is different then index value for that index will be shown but not able to know the value belong to which sublist index, to solve that first one need to make all sublist of same length and then proced with this code.

Sign up to request clarification or add additional context in comments.

Comments

0

You could use list comprehension:

[[row[i] for row in tableData] for i in range(len(tableData[0]))]

[['apples', 'Alice', 'dogs'],
 ['oranges', 'Bob', 'cats'],
 ['cherries', 'Carol', 'moose'],
 ['banana', 'David', 'goose']]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.