SpecialistOff.NET / Вопросы / Статьи / Фрагменты кода / Резюме / Метки / Помощь / Файлы
НазадМетки: python
Set comprehensions allow sets to be constructed using the same principles as list comprehensions, the only difference is that resulting sequence is a set.
Say we have a list of names. The list can contain names which only differ in the case used to represent them, duplicates and names consisting of only one character. We are only interested in names longer then one character and wish to represent all names in the same format: The first letter should be capitalised, all other characters should be lower case.
Given the list:
names = [ 'Bob', 'JOHN', 'alice', 'bob', 'ALICE', 'J', 'Bob' ]
We require the set:
{ 'Bob', 'John', 'Alice' }
Note the new syntax for denoting a set. Members are enclosed in curly braces.
The following set comprehension accomplishes this:
{ name[0].upper() + name[1:].lower() for name in names if len(name) > 1 }