In [1]:
a = {
'x':1,
'y':2,
'z':3
}
b = {
'w':10,
'x':11,
'y':2
}
# In a ::: x : 1 ,y : 2
# In b ::: x : 11,y : 2
In [4]:
# Find keys in common
kc = a.keys() & b.keys()
print('a 和 b 共有的键',kc)
# Find keys in a that are not in b
knb = a.keys() - b.keys()
print('a 有的键 而 b 没有的键',knb)
# Find (key value) pair in common
kv = a.items() & b.items()
print('a 和 b 共有的元素',kv)
In [3]:
# Make a new dictionary with certain keys remove
c = {key : a[key] for key in a.keys() - {'z','w'}}
# c 排除Le {'z' and 'w'}对应的value
print(c)
In [9]:
def dedupe(items):
seen = set()
for item in items:
if item not in seen:
yield item
seen.add(item)
In [10]:
a = [1,3,5,6,7,8,1,5,1,10]
list(dedupe(a))
Out[10]:
In [11]:
len(a)- len(_)
Out[11]:
In [12]:
def dedupe2(items,key=None):
seen = set()
for item in items:
val = item if key is None else key(item)
if val not in seen:
yield item
seen.add(val)
In [13]:
b = [{'x':1,'y':2},{'x':1,'y':3},{'x':1,'y':2},{'x':1,'y':4}]
bd = list(dedupe2(b,key=lambda d: (d['x'],d['y'])))
bd2 = list(dedupe2(b,key=lambda d: (d['x'])))
In [19]:
print('删除满足重复的d[\'x\'],d[\'y\']格式的元素')
bd
# 因为以上格式而又不重复的即为此3 其中{'x':1,'y':2}重复了两次 则被删除
Out[19]:
In [18]:
print('删除满足重复的d[\'x\']格式的元素')
bd2
# 因为以上格式而又不重复的即为此2 b中所有元素 都是以{'x': 1开始的 所以返回第一个element
Out[18]:
In [21]:
ra = [1,1,1,1,1,1,1]
set(ra)
Out[21]:
In [24]:
with open('somefile.txt','r') as f:
for line in dedupe2(f):
print(line)
In [46]:
ns = ''
for nn in range(10):
ns += str(nn)
ns = ns*3
In [49]:
items = [1,2,3,4,5,6,7,8,9]
a = slice(2,4)
In [50]:
items[2:4]
Out[50]:
In [53]:
items[a]
Out[53]:
In [54]:
items[a] =[10,11]
items
Out[54]:
In [55]:
del items[a]
items
Out[55]:
In [56]:
s = slice(5,10,2)
print('s 起始',s.start)
print('s 终末',s.stop)
print('s 公差',s.step)
In [59]:
st = 'helloworld'
a.indices(len(s))
In [2]:
words = [
'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
'my', 'eyes', "you're", 'under'
]
# 找出words 中 出现频率最高的单词
from collections import Counter
word_counts = Counter(words)
# 出现频率最高德3个单词
top_three = word_counts.most_common(3)
print(top_three)
In [3]:
word_counts['not']
Out[3]:
In [4]:
word_counts['eyes']
Out[4]:
In [6]:
morewords = ['why','are','you','looking','in','eyes']
for word in morewords:
word_counts[word] += 1
word_counts['eyes']
Out[6]:
In [7]:
word_counts.update(morewords)
In [8]:
word_counts['eyes']
Out[8]:
In [9]:
a = Counter(words)
b = Counter(morewords)
In [10]:
a
Out[10]:
In [11]:
b
Out[11]:
In [12]:
# combine counts
# 合并
c = a + b
print(c)
In [14]:
# Subtract counts
# 减取
d = a -b
print(d)