25
loading...
This website collects cookies to deliver better user experience
peoples = [
{ 'name': 'John', "age": 64 },
{ 'name': 'Janet', "age": 34 },
{ 'name': 'Ed', "age": 24 },
{ 'name': 'Sara', "age": 64 },
{ 'name': 'John', "age": 32 },
{ 'name': 'Jane', "age": 34 },
{ 'name': 'John', "age": 52 },
]
peoples.sort(key=lambda item: (item['name'], item['age']))
print(people)
#Output
[
{'name': 'Ed', 'age': 24},
{'name': 'Jane', 'age': 34},
{'name': 'Janet','age': 34},
{'name': 'John', 'age': 32},
{'name': 'John', 'age': 52},
{'name': 'John', 'age': 64},
{'name': 'Sara', 'age': 64}
]
[ expression for item in list if conditions ]
mylist = [i for i in range(10)]
print(mylist)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
squares = [x**2 for x in range(10)]
print(squares)
#output
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
def some_function(a):
return (a + 5) / 2
result = [some_function(i) for i in range(10)]
print(result)
#output
[2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0]
filtered = [i for i in range(20) if i%2==0]
print(filtered)
#output
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
import sys
mylist = range(0, 10000)
print(sys.getsizeof(mylist))
#output
48
import sys
myreallist = [x for x in range(0, 10000)]
print(sys.getsizeof(myreallist))
#output
87616
from dataclasses import dataclass
@dataclass
class Card:
rank: str
suit: str
card = Card("Q", "hearts")
print(card == card)
# True
print(card.rank)
# 'Q'
print (card.suit)
# 'hearts'
print(card)
#Card(rank='Q', suit='hearts')
from collections import Counter
print(Counter('abracadabra').most_common(1))
#output
[('a', 5)]
print(Counter('abracadabra').most_common(2))
#output
[('a', 5), ('b', 2)]
print(Counter('abracadabra').most_common(3))
#output
[('a', 5), ('b', 2), ('r', 2)]
dict1 = { 'a': 1, 'b': 2 }
dict2 = { 'b': 3, 'c': 4 }
merged = { **dict1, **dict2 }
print (merged)
#output
{'a': 1, 'b': 3, 'c': 4}
dict1 = { 'a': 1, 'b': 2 }
dict2 = { 'b': 3, 'c': 4 }
merged = dict1 | dict2
print (merged)
#output
{'a': 1, 'b': 3, 'c': 4}