Posts: 1
Threads: 1
Joined: Jul 2017
Jul-18-2017, 06:26 AM
(This post was last modified: Jul-18-2017, 07:14 AM by GhostZero199.)
I try to make a program that sorts words into predifined groups. The thing is how do I make it show me the content that had been transfered to those groups? Thank You!
Update: I did this program but I want to make it with multiple posibilities. "if" statement returns nothing for print.
ConstantinEduard = ('blablabla')
print ("this is a test, input name")
last = input("Numele de familie")
first = input("Prenumele")
print (ConstantinEduard)
Posts: 2,125
Threads: 11
Joined: May 2017
Jul-18-2017, 07:36 AM
(This post was last modified: Jul-18-2017, 07:37 AM by DeaD_EyE.)
Your solution is here:
https://docs.python.org/3.6/library/func...tml#sorted
https://docs.python.org/3/library/iterto...ls.groupby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import itertools
def bycase(word):
if word[ 0 ].isupper():
return 'uppercase'
else :
return 'lowercase'
def byfirstletter(word):
return word[ 0 ].lower()
words = [ 'foo' , 'bar' , 'Baz' , 'baz' , 'Bar' ]
words_sorted = sorted (words, key = bycase)
for key, group in itertools.groupby(words_sorted, bycase):
print ( 'Key:' , key)
for word in group:
print ( 'Word:' , word)
words_sorted = sorted (words, key = byfirstletter)
for key, group in itertools.groupby(words_sorted, byfirstletter):
print ( 'Key:' , key)
for word in group:
print ( 'Word:' , word)
|
The more interesting part is, when you have a list like a table.
For example you have a table with cars and one row has the color.
Sorting by color example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
from itertools import groupby
from operator import itemgetter
cars = [( 'BMW' , '318i' , 'blue' ),
( 'BMW' , '323i' , 'blue' ),
( 'BMW' , '318i' , 'black' ),
( 'BMW' , '323i' , 'blue' ),
( 'BMW' , '323i' , 'black' ),
( 'BMW' , '320i' , 'silver' ),
( 'BMW' , '318i' , 'silver' ),
( 'BMW' , '318i' , 'black' ),
( 'BMW' , '323i' , 'silver' ),
( 'BMW' , '320i' , 'silver' ),
( 'BMW' , '323i' , 'black' ),
( 'BMW' , '318i' , 'blue' ),
( 'BMW' , '323i' , 'blue' ),
( 'BMW' , '323i' , 'blue' ),
( 'BMW' , '323i' , 'blue' )]
sorted_cars = sorted (cars, key = itemgetter( 2 ))
for color, group in groupby(sorted_cars, itemgetter( 2 )):
print ( 'Color:' , color)
for manufacturer, model, color in group:
print (manufacturer, model, color)
|
Hope it helps. Next time you should post example data.
Ok, you edited you original post, my answer is useless in this topic.
Posts: 1,298
Threads: 38
Joined: Sep 2016
(Jul-18-2017, 06:26 AM)GhostZero199 Wrote: "if" statement returns nothing for print.
What 'if' statement?. You need to post your code (between code tags), output (between output tags) and any errors, in their entirety (between error tags).
If it ain't broke, I just haven't gotten to it yet.
OS: Windows 10, openSuse 42.3, freeBSD 11, Raspian "Stretch"
Python 3.6.5, IDE: PyCharm 2018 Community Edition
|