-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlist_comprehension.py
88 lines (51 loc) · 1.57 KB
/
list_comprehension.py
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#list comprehension
def main():
yell('this','is', 'cs50')
def yell(*words):
uppercased=[word.upper() for word in words] #advance feature
print(*uppercased)
if __name__=="__main__":
main()
#list comprehension bit more conditions
students=[{'name':'chandu','house':'cngalore'},
{'name':'gowda','house':'ahandapura'},
{'name':'chandu','house':'cngore'},]
result=[data['name'] for data in students if data['name']=='chandu']
print(result)
#for one below the other
for _ in result:
print(_)
#list comprehension filter
students=[{'name':'chandu','house':'cngalore'},
{'name':'gowda','house':'ahandapura'},
{'name':'chandu','house':'cagore'},]
def is_chandu(c):
return c['name']=='chandu'
place=filter(is_chandu,students)
for a in sorted(place,key=lambda x:x['house']):
print(a['house'])
#dictionary comprehensions
students = ['chandu', 'gowda','spoo']
data = []
for i in students:
data.append({'name':i , 'house':'bang'})
for i in data:
print(i)
#different way for the above same code
#grop of dict
students = ['chandu', 'gowda','spoo']
data=[{'name':student, 'house':'bng'} for student in students]
for i in data:
print(i)
#making a single dict
#dict compreshension
students=['chandu', 'gowda','spoo']
data={i:'bang' for i in students}
print(data)
students=['chandu', 'gowda','spoo']
for i in range(len(students)):
print(i,students[i])
#if we need number should start from 1 then use i+1
students=['chandu', 'gowda','spoo']
for i in range(len(students)):
print(i+1,students[i])