Tips for using python data

Keywords: Lambda Python

1, Filter data from list
For example: get the number of conditions in the collection greater than

lists = [-1,-2,-4,-5,-6,0,1,4,9]
# Find the number greater than 0
str = []
for number in lists:
    if number > 0:
        str.append(number)
print(str)
#[1, 4, 9]

#Tabular form
str = [x for x in lists if x >0]
print(str)

#Pyhton2.7 returns the list, and python 3. X returns the iterator object, that is, the object can then convert the bit list
newStr = filter(lambda x: x >0,lists)
print(list(newStr))

2: Rename each element in the tuple to get its value
For example:

name = 0
age = 1
sex = 2
number = 3

#Define variable to replace index value in list
lists = ("yuanyang","19","nan","139")
#Use lists[name] instead of lists[0]
print(lists[name])
#yuanyang


#Rename tuples by using the named tuple in the standard library
from collections import namedtuple
student = namedtuple("students",["name","age","sex","number"])
str = student("zhangsan","20","nan","9898")
print(str)
#students(name='zhangsan', age='20', sex='nan', number='9898')
print(str.name)
#zhangsan

3: Frequency of elements in statistical sequence
For example:

list = [12,5,6,4,6,5,5,7,8,4,3,1,2,6]
#Generate a new dictionary based on key
str = dict.fromkeys(list,0)
print(str)
#{12: 0, 5: 0, 6: 0, 4: 0, 7: 0, 8: 0, 3: 0, 1: 0, 2: 0}
for number in list:
    str[number] += 1
print(str)
#{12: 1, 5: 3, 6: 3, 4: 2, 7: 1, 8: 1, 3: 1, 1: 1, 2: 1}


#Use Counter in standard library to count data
from collections import Counter
#Find the number of occurrences of each letter
newStr = Counter(list)
print(newStr)
#Counter({5: 3, 6: 3, 4: 2, 12: 1, 7: 1, 8: 1, 3: 1, 1: 1, 2: 1})
#3 bits with the highest frequency
counterStr = newStr.most_common(3)
print(counterStr)
#[(5, 3), (6, 3), (4, 2)]

4: Sort the items in the dictionary according to the size of the values in the dictionary
For example:

from random import randint
#Create a dictionary
str = {x: randint(60,100) for x in "xyzabc"}
#{'x': 96, 'y': 94, 'z': 76, 'a': 79, 'b': 88, 'c': 60}
print(str)
#Convert dictionary to a new tuple
newStr = zip(str.values(),str.keys())
#sorted: sorting key values by default
print(sorted(newStr))
#[(60, 'b'), (67, 'y'), (69, 'x'), (69, 'z'), (78, 'c'), (94, 'a')]


#The second way is to customize the sorting rules of specifications
newSortStr = sorted(str.items(),key=lambda x:x[1])
print(newSortStr)

5: Query the common keys that appear in the dictionary
For example:

from random import randint,sample
#Extract elements of a common key from multiple dictionaries
#Sample (sequence a, n)
#Function: randomly extract n elements from sequence a, and generate n elements to return in the form of list.

str = sample("abcdefg",randint(3,6))
print(str)
#['f', 'a', 'd', 'g', 'b']
s1 = {x: randint(1,4)for x in str}
print(s1)
#{'a': 4, 'c': 2, 'e': 4}
s2 = {x: randint(3,6)for x in str}
s3 = {x: randint(4,7)for x in str}
newduple = []
for x in s1:
    if x in s2 and x in s3:
        newduple.append(x)
print(newduple)

#The second way
dict1.viewkeys()&dict2.viewkeys()&dict3.viewkeys() The premise is to know which dictionaries are involved

#Mode 3
 map(dict.viewkeys,[dict1,dict2,dict3]) Get dictionary's viewkeys aggregate
 print reduce(func,map(dict.viewkeys,[dict1,dict2,dict3])) Finding common key by finding intersection

6: Keep dictionaries in order
For example:

from collections import OrderedDict
#Get an ordered empty dictionary
dicts = OrderedDict()
dicts["angle"] = (1,90)
dicts["dimu"] = (3,78)
dicts["baby"] = (2,80)
for x in dicts:
     print(x)

Seven: realize the historical record function of users
For example:

#duque in the standard collection is a two terminal circular queue
from collections import deque
#Only the latest three data are kept in the new queue
newList = deque([],3)
newList.append(1)
newList.append(2)
newList.append(3)
print(newList)
#eque([1, 2, 3], maxlen=3)

8, Reverse iteration of list
For example:

lists = [1,2,3,4,5]
newList = lists[::-1]
print(newList)
#[5, 4, 3, 2, 1]

#list.reverse() the method does not return a value, but it sorts the elements of the list in reverse.
lists.reverse()
print(lists)
#[5, 4, 3, 2, 1]

#reversed returns the memory address of an iterator object
str = reversed(lists)
print(list(str))
#[5, 4, 3, 2, 1]
'''

//9:  for loop iterates multiple iteratable objects
//For example: parallel iteration serial iteration
#Using zip to merge multiple iteratable objects, each iteration returns a tuple parallel iteration
chinese = [1,2,3,4]
math = [6,2,3,4]
englist = [1,8,3,4]
total = []
for c,m,e in zip(chinese,math,englist):
    total.append(c+m+e)
print(total)
#[8, 12, 9, 12]

#Serial iteration uses itertools.chain in the standard library to connect multiple iteratable objects
from  itertools import chain
for s in chain(chinese,math,englist):
    if s >5:
        print(s)
        #6,8

Posted by theironchef on Mon, 30 Dec 2019 10:21:38 -0800