List, tuple, string, set, dictionary summary
This week, I learned five container types: list, tuple, string, set and dictionary. The following is a simple summary of the five container types to make people better understand them.
Representation in python
List ------------ > [element, element, element]
Tuple ------------ > (element, element, element)
String (STR) ---------- > 'character data'
Set -------------- > {element, element, element}
Dictionary (dict) ----- > {key: value, key: value}
give an example:
# list list1 = [] # Represents an empty list list2 = [1, 2, 3, 4] # Define the list with [], and the elements in it can be any type of data # tuple tuple1 = ('apple', 'banana', 'grape') # Define tuples () tuple2 = (100,) # Add a comma to a tuple tuple3 = () # Empty tuple print(tuple3, type(tuple3)) # character string str1 = 'hello, world' # To define a string, you need to enclose a single character or multiple characters with ',' ', or' '' ' # aggregate set1 = {1, 2, 3, 4} # Define set with {} set2 = set() # Create an empty collection # Dictionaries student1 = { # It consists of keys and values separated by: 'id': 1010, 'name': 'Xiao Ming', 'sex': 'True', 'birthday': '2000-1-1' }
variability
1: The elements in the list and dictionary are variable. The operations of adding, deleting, querying and modifying are supported
The list supports subscript operation The dictionary finds and operates the corresponding value through the key
2: The elements in tuples, strings and collections are immutable, and only query operations are supported. Tuples and strings can find elements by slice index. The collection is unordered and cannot find elements by subscript
list | character string | tuple | aggregate | Dictionaries |
---|---|---|---|---|
variable | Immutable | Immutable | Immutable | The dictionary is mutable, and the keys in the dictionary must be immutable |
Orderly | Orderly | Orderly | Disorder, in which all elements are not repeated | Unordered, search by key or value |
Some methods often used
sort
It is often used in lists and dictionaries. The list can be sort, sorted, and dictionary
Only sorted is supported
list1 = ['1', '2', '3', '4'] list1.sort(key=int, reverse=True) # reverse=True sorts from high to low, specifying that the sort is sorted by int type print(list1) stocks = { 'AAPL': 191.88, 'GOOG': 1186.96, 'IBM': 149.24, 'ORCL': 48.44, 'ACN': 166.89, 'FB': 208.09, 'SYMC': 21.29 } x = sorted(stocks, key=stocks.get, reverse=True) # Sort from large to small by the value of the dictionary key. The last output is the dictionary key print(x)
If no key is specified, the dictionary sorts the keys of the dictionary by default If reverse is not specified, the default sorting is from small to large.
Random sampling and out of order, finding the maximum and minimum
random.sample() samples the list without putting it back
random.choices() performs a put back sampling of the list
The choice function selects an element from the list
shuffle function scrambles order
max() for maximum
min() minimum
count() counts the number of occurrences
example
Save 52 playing cards in a list, shuffle, distribute the cards to three players according to the licensing method of fighting the landlord, and give the additional 3 cards to the first player (landlord), so as to display the cards in each player's hand
import random kinds1 = ['♠', '♣', '♥', '♦'] kinds2 = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'] cards = [f'{i}{j}' for i in kinds1 for j in kinds2] # Combine numbers with decors cards.append('king') cards.append('Xiao Wang') print(cards) print(len(cards)) random.shuffle(cards) # Randomly shuffle the order of cards # Nested list (the elements in the list are also lists) players =[[] for _ in range(3)] # Create three empty lists to represent three players for _ in range(17): for player in players: player.append(cards.pop()) # Take out the cards players[0] += cards # Give the remaining three cards to the first player # players[0].extend(cards) # Merge the elements of one list into another for player in players: # Sort the elements of the list player.sort(key=lambda x: x[1]) for card in player: print(card, end=' ') print()
Example 2:
Save the scores of 5 students and 3 courses
import random names = ['Xiao Hei', 'poppin ', 'Xiao Hong', 'millet', 'Xiao Ming'] courses = ['language', 'mathematics', 'English'] scores = [[random.randrange(50, 101) for _ in range(len(courses))] for _ in range(5)] print(scores) # Find the average score of each student for i, name in enumerate(names): print(f'{name}Average grade of students:{sum(scores[i]) / len(courses):.1f}') #Seek the highest and lowest scores for each course for j, course in enumerate(courses): temp = [scores[i][j] for i in range(len(name))] print(f'{course}Highest score:{max(temp)}') print(f'{course}Minimum score:{min(temp)}')
Example 3:
Output 10 lines of Yang Hui triangle
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
x = int(input('Enter a number:')) nums =[[] for _ in range(x)] for i in range(x): nums[i].append(1) if i > 0: for j in range(1, i): nums[i].append(nums[i - 1][j - 1] + nums[i - 1][j]) nums[i].append(1) for num in nums[i]: print(num, end='\t') print()
Results:
Enter a number: 10 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 1 8 28 56 70 56 28 8 1 1 9 36 84 126 126 84 36 9 1
Method 2:
x = int(input('Enter a number:')) nums = [[0] * x for _ in range(x)] for i in range(x): nums[i][0] = 1 nums[i][i] = 1 for j in range(1, i): nums[i][j] = nums[i - 1][j - 1] + nums[i - 1][j] # for i in range(x): # for j in range(i + 1): # print(nums[i][j], end='\t') # print(' ') for i in range(x): for j in range(x - i): print(end=' ') for k in range(i + 1): print(nums[i][k], end=' ') print(' ')
result:
Enter a number: 10 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 1 8 28 56 70 56 28 8 1 1 9 36 84 126 126 84 36 9 1
Example 3:
There are many duplicate elements in a list. Write a piece of code to remove the duplicate elements in the list
Method 1:
list1 = [1, 2, 3, 2, 3, 4] list2 = [] for x in list1: if x not in list2: list2.append(x) print(list2)
Method 2:
Convert a list to a collection, and then convert it to a collection
set1 = set(list1) list2 = list(set1) print(list2)
Example 4:
There is a list of integers to find the most frequent elements in the list
# Method 1 d = list1.count(list1[0]) for i in list1: if list1.count(i) > d: d = list1.count(i) for x in list1: if list1.count(x) == d: print(x) list1.remove(x)
Method 2
items, max_count = [list1[0]], list1.count(list1[0]) for num in list1[1:]: if list1.count(num) > max_count: items.clear() items.append(num) max_count = list1.count(num) elif list1.count(num) == max_count: if num not in items: items.append(num) for x in items: print(x)
Example 5:
Generate 10 groups of random verification codes (composed of numbers and English letters, with a length of 4)
import random import string list1 = string.ascii_letters + string.digits # list = '0123456789abcdefghijklmnopqrstuvwsyzABCDEFGHJIKLMNOPQRSTVUWSYZ' for _ in range(10): x = random.choices(list1, k=4) print(''.join(x))
Example 6:
There is a list of integers, in which an integer appears more than half times. Please find the element (considering efficiency, nested loops are not used)
list1 = [1, 3, 3, 3, 2, 2, 3] counter, temp = 0, None for num in list1: if counter == 0: temp = num counter = 1 else: if num == temp: counter += 1 else: counter -= 1 print(temp) """ process: num 1 3 3 3 2 2 3 temp 1 1 3 3 3 3 3 counter 1 0 1 2 1 0 1 """
Example 7:
Enter a paragraph and count the number of occurrences of each word
str1 = 'Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.' str2 = str1.lower() str2 = str2.replace(',', '').replace('.', '') str2 = str2.split(' ') dict2 = {x: 0 for x in str2} for word in str2: dict2[word] += 1 for key, value in dict2.items(): print(f'{key}There it is{value}second')