+ 1

Setting fixed width display of a list

I'm trying to display a list which has several lines in it, each with several items, as a neat "table" where each "column" has a fixed width. For example: John Watson assistant 50 Single Sherlock Holmes detective 40 Single I've looked around for solutions and they're all too complicated for my level... I've only just started Python but this is an assignment I've got and we weren't given much guidelines at all so I'm left trying to figure everything out by myself. I've tried something like: print(surname,+',', name, '%10s' % job, '%10s' % age, '%10s' % status) Where all the names in the brackets were previously saved as variables with values input by the user upon request. That worked, it looked neat. But then I realized once I have more than just one row it will be misaligned. So the same method won't work for a whole "table". I've tried something like this then: (Previously typed a function to open a text file and read and import the lines into a newly created list) for i in employees: x = 32-(len(i[0]+i[6])) print(i[6] + ',', i[5], i[4], i[3], ' '*x + i[0], i[2], i[1]) but I got an error saying the index list is out of range. So I've run out of ideas. Basically I've got a small text file with a few lines with words separated by spaces. Each word represents a specific thing, such as job, age, status, surname etc. The first names vary - some people have 1 name, others have 4. So some lines have 7 items while others just 4. My task is to display the rows in the format: Surname, first names|job|age|status. There must not be several different values for first name. They must be displayed under the same "column" and connected with the surname by a comma. Now I can't even figure out how to display a whole set of different values with a fixed width, let alone how to get around merging several words into just one fixed width "column". Any help would be greatly appreciated. And remember I am FAR FROM advanced. I have ju

6th Dec 2017, 3:53 AM
Laura
Laura - avatar
7 ответов
0
# assuming you have read your lines in and got a list of lists or similar structure data=[['John Watson','assistant','50','Single'], ['Sherlock Holmes','detective','40','Married'], ['Timmy','cop','103','Married']] # find the max width of each column +1 col_one_max = max([len(item[0])for item in data])+1 col_two_max = max([len(item[1])for item in data])+1 col_three_max = max([len(item[2])for item in data])+1 col_four_max = max([len(item[3])for item in data]) # look here https://docs.python.org/3.4/library/string.html # to start experimenting with the formatting options # you can use keywords for setting column width and <^> for relative # placements in the column and much more. # the example is left aligned < and filled with blank space. for item in data: print('{:<{width1}}{:' '<{width2}}{:<{width3}}{:<{width4}}'.format(*item, width1=col_one_max, width2=col_two_max, width3=col_three_max, width4=col_four_max))
6th Dec 2017, 12:51 PM
richard
0
Could I get more help on this? I don't really understand everything you typed, even though I pasted it into my code and it worked (partially). I'd like to understand what each line means. I've got so many questions. Plus, my list actually has more than 4 columns so I tried simply editing your code to add more columns, all with the same identical way of typing and I'm getting errors...
6th Dec 2017, 7:19 PM
Laura
Laura - avatar
0
I now see you have yet to complete the python course. Best do that first. There's no easy way to learn but if what you are attempting to do is beyond you try to break the problem into smaller steps and become familiar with how to to those steps as second nature. In your case get a grasp on 1 - what .format() can do 2- list comprehensions 3- * unpacking notation Clearly you are on the right track with all the things you listed in your post as it indicates someone prepared to experiment. Don't be disappointed if the first ideas for a project you think you can do turn out to be too hard. Repeated practice with simple things makes it easier. Try https://www.codingame.com/home for a structured environment that gives feedback on your code when you advance a little further.
6th Dec 2017, 10:07 PM
richard
0
That's just the thing. I'm trying to break it down into smaller steps because I want to understand how everything works but all the information I find on .format() for example, is too hard to get. Maybe I'm just slow but I don't get it. Our lecture slide gave this example for how to format a line(edited for my assignment): employees = [] employees.append((payroll, salary, job, name, surname)) lengths = [] for p in employees: lengths.append(len(p.name)) width = max(30) for p in employees : print("{0:{2}.{2}s} {1:10d}".format(p.name, p.salary, width)) #gives error AttributeError: 'tuple' object has no attribute 'name' I don't know where to go for whatever previous steps I need to learn to understand the format explanations on sites such as https://docs.python.org/3.4/library/string.html
7th Dec 2017, 6:04 PM
Laura
Laura - avatar
0
# creating a collection of employee objects as list of dictionaries employees = [] employees.append({'payroll':45, 'salary':21000, 'job':'cleaner', 'name':'Jo', 'surname':'Blo'}) employees.append({'payroll':12, 'salary':1500, 'job':'builder', 'name':'Frederic', 'surname':'Lowe'}) # scanning the collection to determine required max width of the name column lengths = [] for p in employees: lengths.append(len(p['name'])) width = max(lengths) # using format to utalize width of name column for p in employees : print("{0:{2}} {1:5d}".format(p['name'], p['salary'], width)) ''' based on the syntax suspect your example is actually using a user defined class with properties name, salary ect. Either way Dictionaries , Classes or another structure have fun experimenting there is no single answer to understanding your assignment other than practice over time. try https://www.codewars.com/ as a simple tool to learn the basics, it's not as high quality as codingame but there are far more tests available to try out very basic comprehension of specific languages it's practice on sites such as those that can help on the way to understanding the offical python documents. '''
7th Dec 2017, 8:45 PM
richard
0
Thanks a lot for all the answers! I'll try to go through all the info and sites until I understand.
7th Dec 2017, 11:05 PM
Laura
Laura - avatar
0
Your code still doesn't work. I'm gonna try to stalk my lecturer for answers lol
11th Dec 2017, 11:29 PM
Laura
Laura - avatar