python collection (set) and a dictionary (dictionary) usage resolve

Table of Contents generated with DocToc

ditctaionary and set

hash Introduction

  hash computer is a very common way to find the way, it can support constant-time insert, remove, find, but for findMin, findMax, sort and other operations to support is not very good, specifically why;

  In fact, through the hash value to find the key, it can be simply understood as a value are present in the array, with a key every time you calculate the corresponding array index can be obtained, i.e., index = f (key) is not clicking to find the location where the child element of it!

-Set collection

  Collection (set) is a type of container, in no particular order elements, and the element value will not be repeated.
  Amount set by the literal brace} {
EG:

  • {1,5,7}
  • {'apple', 'orange', 'pear', 'banana'}

create

  • A variable assignment directly to the literal set
    fruit = { 'apple', ' orange', 'pear', 'banana'}

  • Using the set () creates an empty set
    emp = set ()
    Note: emp = {} # Create an empty dictionary

  • Using the set () converts a list or set of tuples into a
    prime = set ([1,3,5,7,11])
    The result is:
    {1, 3, 5, 7, 11}

Operations and collection element access

Can add and delete collection element with add () and remove ()
you can use the min (), max (), len () and the sum () of the collective operation.
Elements within the sets are unordered, so as not to access a collection of elements like list by index.

  • Implement various elements through the collection of circulating
s = {2,3,5,7,11}
for i in s:
    print(i,end='')
#输出:
#235711
  • Operators in and not in an element for determining whether the set.
s = {2,3,5,7,11
print(5 in s)
print(4 not in s)
输出:
True
True

Subset, superset, determines the relative

  • If the collection element s1, s2, likewise in the collection, called s1 s2 is a subset, superset s1, s2.
    Use s1.issubset (s2) to determine whether a subset of s1 and s2.
    Use s2.issuperset (s1) to determine whether s1 s2 superset.
s1 = {2,3,5,7}
s2 = {1,2,3,4,5,6,7}
print(s1.issubset(s2))
print(s2.issuperset(s1))
输出:
True
True
  • Use relational operators == and! =
    - Analyzing set includes two identical elements or not.

  • Use relational operators <, <=,>,> =.
    - if s1 is a subset s2, then s1 <s2 is True
    - If s1 is a subset s2, then s1 <= s2 is True
    - If s1 is true superset s2, then s1> s2 is True
    - If s1 is s2 superset, then s1> = s2 is true
    - Note: s1 is s2 proper subset mean s1 is a subset of s2, but s2 at least elements a s1 does not exist; s1 is true for s2 means superset s1 s2 is a superset of, but there s1 s2 least one element that does not exist.

  • It is set by the operator or function set union, intersection, difference, and symmetric difference set operations.

Operation function Operators Explanation
Union union() | The same mathematical union
Intersection intesection () & Intersection with mathematics
Difference set difenrence () - s2 s1-s2 now not appear s1
Symmetric difference symmertric_diference () ^ ^ s1 s2 = s1

Dictionary -dictionary (map)

  A dictionary is a collection of indexed with a "key" to store data. A key and its corresponding data entry in a dictionary form. The key is the dictionary used for the hash function, it is necessary immutable objects, such as numbers, strings, tuples; not as a key variable of the object, such as a list, dictionary, set

Create dictionary

  • Braces {} are represented, each partition element key data and colon. {} May be used or dict () to create an empty dictionary.
students = {3180101:’张三’, 3180102:’李四’, 3180105:’王五’, 3180110:’赵六’}
d={'math': '0001', 'python': '0002', 'c': '0003'}

d=dict([("math","0001"),("python","0002"),("c","0003")])

d=dict(math="0001",python="0002",c="0003")

Basic operations dictionary

  • Access and modify entries
    directly with [] operator, with <Dictionary> [key] form, data corresponding to the access key.
score = {'张三':78, '李四':92}
print(score['张三'])#访问score中键为'张三'的数据
score['李四'] = 89#把score中键为'李四'的数据修改为89
score['王五'] = 100#score中没有键为‘王五’的元素,则增加一项,键为’王五’,数据为100。
print(score)
输出:
78
{'张三': 78, '李四': 89, '王五': 100}
  • Delete entry
    del dictName [key]
    If the key does not exist, an exception will be thrown KeyError

  • Traversal Dictionary

# 循环
score = {'张三':78, '李四':92, '王五':89}
for name in score:
    print(name + ':' + str(score[name]))

#用items()
for key,value in score.items():
   print(key + ':' + str(value))
输出:
张三:78
李四:92
王五:89
  • Dictionary size len ()

  • Detection, in and not in the detection key is in the dictionary

  • And with ==! = Comparison 2 are the same dictionary (keys and values ​​are the same)

  • Dictionary of commonly used functions
    | Function | Description |
    |: - |: - |
    | Keys () | Returns the sequence of all the key component |
    | values () | return sequence of all values consisting of |
    | items () | return goods a sequence , each of which is a tuple, (key, value) |
    | the Clear () | delete all entries |
    | GET (key, value) | returns the value of this key corresponds, as can not find the return None |
    | POP ( key) | returns the value corresponding to the key, delete this entry |

Variable objects and immutable

Variable objects and immutable object is the core concept of the Python language.

  • Immutable object pointed to memory values ​​can not be changed. When changing a variable time, since the value to which it refers can not be changed, which is equivalent to a copy of the original value after the change, which will open up a new address, the variables point to the new address.
  • Variable object, the value of the object points in the memory can be changed. After variable (to be exact quote) change, in fact, the value of its meaning changed directly, copying did not happen, nor open up a new address.
  • Immutable data types to create an immutable object, creating a variable data variable object type
  • Variable types: lists, sets, dictionaries
  • Immutable types: integer, floating point, complex, character string, the amount of logic (True False), tuple
  • Different types of objects and data conversion logic value
    type of data True False
    Integer Non-0 0
    Float Non-0 0.0
    plural Non-0 0 + 0j
    String non empty ""
    Logical volume True False
    List non empty []
    Tuple non empty ()
    set non empty set()
    dictionary non empty {}

application

set

  • List deduplication
#去重,但不能保证保持原有顺序
mailto = ['cc', 'bbbb', 'afa', 'sss', 'bbbb', 'cc', 'shafa']
addr_to =list(set(mailto))
print(addr_to)
#result ['shafa', 'cc', 'sss', 'afa', 'bbbb']
#排序后保证保持原有顺序
addr_to.sort(key = mailto.index)
print(addr_to)
#result ['cc', 'bbbb', 'afa', 'sss', 'shafa']

Find the saddle point

n=int(input())
a=[]
for i in range(0,n):
      b=input().split()
      a.insert(i,b)
c=[]
d=[]
for i in range(0,n):
    maxa=max(int(a[i][j]) for j in range(n))
    mina=min(int(a[k][i]) for k in range(0,n))
    c+=[(i,j) for j in range(n) if int(a[i][j])==maxa]
    d+=[(k,i) for k in range(n) if int(a[k][i])==mina]
c=list(set(c)&set(d))
if (c!=[]):
   print(c[0])
else:
   print("NONE")

dictionary

  • Alternative language dictionaries branch
#输入一个1到7的数字,输出对应的星期名的缩写
days={1:"Mon",2:"Tue",3:"Wed",4:"Thu",5:"Fri",6:"Sat",7:"Sun"}
num=int(input())
print(days[num])

result={"+":"x+y","-":"x-y","*":"x*y","/":'''x/y if y!=0   \
        else "divided by zero"'''}
x=int(input())
z=input().strip()
y=int(input())
r=eval(result.get(z))#计算表达式的值
if type(r)!=str:
    print(format(r,'.2f'))
else:
    print(r)

  • Dictionary count

eg:1

#输入一行字符,求字符”a”,”b”和”c”出现的次数

diccount={char:0 for char in "abc"}   #字典初始化
s=input()
lst=[char for char in s if  
      ord("a")<=ord(char)<=ord("c")]
for char in lst:
    diccount[char]+=1
print(diccount)

eg2:

#输入一行字符,求每个字符出现的次数
#建字典dicchar,键是字符,值是字符出现的次数。由于不能预知出现哪些字符,所以不能预先初始化字典
#注意字典的get函数:get() 函数返回指定键的值,如果值不在字典中返回默认值。countchar.get(c,0)函数返回键为c的值, 不在字典中返回0。

str=input()
countchar={}

for c in str:
    countchar[c]=countchar.get(c,0)+1
print(countchar)

eg:

#求列表中两数之和等于指定数的下标
'''
Given nums = [2, 11,7, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 2].
'''
nums = [2, 6, 11, 15,7,8]
target = 9


hm = dict()
for i in range(len(nums)):
    if nums[i] in hm:
        print(hm[nums[i]], i)
        break
    hm[target - nums[i]] = i
print([2, 6, 11, 15,7,8])
print(hm)
  • Dictionary nested list
books=[
        {"name":u"C#从入门到精通","price":25.7,"store":u"卓越"},
        {"name":u"ASP.NET高级编程","price":44.5,"store":u"卓越"},
        {"name":u"Python核心编程","price":24.7,"store":u"当当"},
        {"name":u"JavaScript大全","price":45.7,"store":u"当当"},
        {"name":u"Django简明教程","price":26.7,"store":u"新华书店"},
        {"name":u"深入Python","price":55.7,"store":u"新华书店"},
      ]

print(min([item["price"] for item in books ]))
#24.7
books[0]['name']
#C#从入门到精通
  • Nested dictionary
users = {'aeinstein': {'first': 'albert',
                       'last': 'einstein',
                       'location': 'princeton'},
         'mcurie': {'first': 'marie',
                    'last': 'curie',
                    'location': 'paris'},
         }

for username, user_info in users.items():
    print("\nUsername: " + username)
    full_name = user_info['first'] + " " + user_info['last']
    location = user_info['location']

    print("\tFull name: " + full_name.title())
    print("\tLocation: " + location.title())
    '''
Username: aeinstein
Full name: Albert Einstein
Location: Princeton

Username: mcurie
Full name: Marie Curie
Location: Paris
    '''
  • Map and dictionary
# %% 求图的顶点数,边数,边的总长  空字典{},空集合 set()
d={"start": {1:1,2:2,3:4},  #第一个点为“start”,一条边指向1,长度为1,一条指向2,长度为2,一条指向3,长度为4
   1:{3:5},
   2:{"end":8,3:78},
   3:{2:4,"end":8},
   "end":{}   }
v=set();     e=set()    ;s=0           #顶点的集合,边点的集合
for key,value in d.items():
    v.add(key)
    if type(value)==dict:
        for key1,value1 in value.items():
            v.add(key1)
            e.add((key,key1))
            s+=value1

print(len(v),len(e),s)
#5 8 110
  • Assembly dictionary
id = "IAD"
location = "Dulles Intl Airport"
max_temp = 32
min_temp = 13
precipitation = 0.4


print("{id:3s} : {location:19s} : {max_temp:3d} / {min_temp:3d} /{precipitation:5.2f}".format(
   id=id, location=location, max_temp=max_temp,
   min_temp=min_temp, precipitation=precipitation))

data = dict(
       id=id, location=location, max_temp=max_temp,
       min_temp=min_temp, precipitation=precipitation
       )
print("{id:3s} : {location:19s} : {max_temp:3d} / {min_temp:3d} /{precipitation:5.2f}".format_map(data))

#IAD : Dulles Intl Airport :  32 /  13 / 0.40
#IAD : Dulles Intl Airport :  32 /  13 / 0.40
#date={'id': 'IAD', 'location': 'Dulles Intl Airport', 'max_temp': 32, 'min_temp': 13, 'precipitation': 0.4}

Reference Documents

[python official document] https://docs.python.org/3.8/library/stdtypes.html#set-types-set-frozenset

Note: if infringement contact the author to delete posts

Guess you like

Origin www.cnblogs.com/qwfand/p/12627393.html