simple lists

This is the place for queries that don't fit in any of the other categories.

simple lists

Postby el_manu » Mon Sep 02, 2013 8:27 am

i wanna make a program that reads in input. stores it as a list and then prints each word of the list on seperate lines..

i have done:
Code: Select all
b = input('Students: ')
b = b.split()
d = b.sort()
a = len(b)
c = 0
print("Class Roll")
while c != a:
  f = int((a-a)+c)
  print(d[f])
  c = c + 1


but i can't do line 9: (
Code: Select all
print(d[f])


any better ways to do this
el_manu
 
Posts: 87
Joined: Mon Aug 19, 2013 8:30 am

Re: simple lists

Postby Mekire » Mon Sep 02, 2013 9:22 am

Ok. So first of all; the sort method of lists works in place. It doesn't return anything but rather changes the original list.

For example if I want a sorted list, this won't work:
Code: Select all
>>> my_list = [2,7,3,9,4,67,1,2]
>>> my_list = my_list.sort()
>>> print(my_list)
None
>>>

You need to do it like this:
Code: Select all
>>> my_list = [2,7,3,9,4,67,1,2]
>>> my_list.sort()
>>> print(my_list)
[1, 2, 2, 3, 4, 7, 9, 67]
>>>

Next, printing every element in the sorted list is the same as with any iterable. Use a for loop:
Code: Select all
my_input = input('Students: ')
my_list = my_input.split()
my_list.sort()

for element in my_list:
    print(element)

You can also do it using join:
Code: Select all
my_input = input('Students: ')
my_list = my_input.split()
my_list.sort()

print("\n".join(my_list))

-Mek
User avatar
Mekire
 
Posts: 1140
Joined: Thu Feb 07, 2013 11:33 pm
Location: Asakusa, Japan

Re: simple lists

Postby el_manu » Mon Sep 02, 2013 9:34 am

thks
el_manu
 
Posts: 87
Joined: Mon Aug 19, 2013 8:30 am

Re: simple lists

Postby el_manu » Mon Sep 02, 2013 11:07 am

also a program where it asks for input and the program keeps doing that until a space is entered. And then it prints the amount of unique statements.
Code: Select all
Word: A = Dingo
Word: Took = My
Word: Stupid = Baby
Word: ok = understood
Word: A = Dingo
Word:
4 unique statement(s)!


How do i do this...read the lines in a while loop, check if the line is already in the list. If it isn't enter it into the list.
and then at the end, my list should just be the unique lines.
el_manu
 
Posts: 87
Joined: Mon Aug 19, 2013 8:30 am

Re: simple lists

Postby el_manu » Mon Sep 02, 2013 1:42 pm

is what i wrote for my prevoius post how i go about doing the question??
el_manu
 
Posts: 87
Joined: Mon Aug 19, 2013 8:30 am

Re: simple lists

Postby Mekire » Mon Sep 02, 2013 1:49 pm

Basically. You could also consider using a set as sets don't allow duplicates.

Code: Select all
entries = set()
my_input = input("Enter something: ")
while my_input:
    entries.add(my_input)
    my_input = input("Enter something: ")


-Mek
User avatar
Mekire
 
Posts: 1140
Joined: Thu Feb 07, 2013 11:33 pm
Location: Asakusa, Japan


Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 2 guests

cron