a = (1)
type(a)
int
a = (1,)
type(a)
tuple
from collections import namedtuple
MyHost = namedtuple('MyHost',['host', 'ip'])
MyHost
__main__.MyHost
MyHost(host='cn', ip='1.2.3.4')
MyHost(host='cn', ip='1.2.3.4')
Hosts = [
('us','2.2.2.2'),
('hk','3.3.3.3')
]
[ MyHost._make(h) for h in Hosts ]
[MyHost(host='us', ip='2.2.2.2'), MyHost(host='hk', ip='3.3.3.3')]
from ast import literal_eval as make_tuple
make_tuple('(1,2)')
(1, 2)
[1,]
[1]
list(map(lambda x: x*2, [1,2,3]))
[2, 4, 6]
sorted(['ad','abd','b'])
['abd', 'ad', 'b']
sorted({'ad','abd','b','b'})
['abd', 'ad', 'b']
a1 = ["live", "arp", "strong"]
a2 = ["lively", "alive", "harp", "sharp", "armstrong"]
[s1 for s1 in a1 for s2 in a2 if s1 in s2]
['live', 'live', 'arp', 'arp', 'strong']
students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10),]
sorted(students, key=lambda s : s[2]) # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
[1,2,3][::-1]
[3, 2, 1]
lst1 = [1, 2, 3, 4, 1, 4, 1]
print( [ {i: lst1.count(i)} for i in set(lst1) ] )
from collections import Counter
c = Counter(lst1)
c
[{1: 3}, {2: 1}, {3: 1}, {4: 2}]
Counter({1: 3, 2: 1, 3: 1, 4: 2})
c.most_common()
[(1, 3), (4, 2), (2, 1), (3, 1)]
delete_nth = lambda order, max_e: [x for i, x in enumerate(order) if order[:i].count(x) < max_e]
delete_nth([20,37,20,21],1) #item appears at most 1 times
[20, 37, 21]
a = [1,2,3,2,1]
a.remove(1) #insert, remove or sort only modify the list have no return value printed
a.insert(2, -1) # 2 is index, -1 is value
b = [1,2,3,2,1]
b.pop(1) # 1 is index
print(a)
a.reverse()
print(a)
print(b)
a+b
[2, 3, -1, 2, 1] [1, 2, -1, 3, 2] [1, 3, 2, 1]
[1, 2, -1, 3, 2, 1, 3, 2, 1]
{x for x in range(8)} # set
{0, 1, 2, 3, 4, 5, 6, 7}
{1,3,2} - {1}
{2, 3}
{1,3,2} & {1}
{1}
{1,3,2} | {1, 4}
{1, 2, 3, 4}
print(1 ^ 1, 0 ^ 0, 1 ^ 0, 0 ^ 1)
{1,3,2} ^ {1, 4} # not in both
0 0 1 1
{2, 3, 4}
a = {'i': 30,'u': 20,'she':44}
b = {'i': 31,'u': 21,'he': 55}
c = a.copy()
c.update(b)
c
{'he': 55, 'i': 31, 'she': 44, 'u': 21}
from collections import defaultdict
d = defaultdict(list)
d[1] = 3 # int, not default list
d[1] = [4]
d[1].append(5)
d[2] #set to default []
d
defaultdict(<class 'list'>, {1: [4, 5], 2: []})
i = defaultdict(int)
i[1]
0
from collections import OrderedDict
d = {1:'a', 3:'c', 2:"b"}
d
{1: 'a', 2: 'b', 3: 'c'}
OrderedDict(d)
OrderedDict([(1, 'a'), (3, 'c'), (2, 'b')])
d[3]
'c'