1. The ancestor
If there is only one element in the tuple and there is no comma, the data type of the data is the same as the element in it.
tu1 = ( ' laonanhai ' ) tu2 = ('laonanhai',) print(tu1, type(tu1)) print(tu2, type(tu2)) tu1 = (1 ) tu2 = (1,) print(tu1, type(tu1)) print(tu2, type(tu2))
2. List
Use the algorithm to delete (all elements corresponding to odd indices)
Method 1: Error display! ! !
l1 = [111, 222, 333, 444, 555, ]
for index in range(len(l1)):
print('delete the previous index:%s' % index)
print('delete the previous l1:%s' % l1)
if index % 2 == 1:
del l1[ index]
print('index after deletion: %s' % index)
print('l1 after deletion: %s' % l1)
print(l1)
Method 2: Correct
l1 = [111, 222, 333, 444, 555, ]
for index in range(len(l1)-1, -1, -1):
if index % 2 == 1:
del l1[index]
print(l1)
When looping through a list, it is best not to change the size of the list, it will affect your final result.
3. Dictionary
Usage of fromkeys
dic = dict.fromkeys('abc',666) print(dic) dic = dict.fromkeys([11,22,33],666) print(dic) dic = dict.fromkeys([1,2,3],[]) dic[ 1].append(666 ) # If you add an element to the list then the value of all keys will be incremented print (dic)
In the loop dict, it is best not to change the size of the dict, which will affect the result or report an error.
# delete key pair value with "k" in key
dic = { ' k1 ' : ' v1 ' , ' k2 ' : ' v2 ' , ' k3 ' : ' v3 ' , ' name ' : ' alex ' } for i in dic: if ' k ' in i: del dic[i]
# The dictionary cannot delete the key pair value in it during the loop! ! !
# Correct way
dic = {'k1': 'v1', 'k2': 'v2','k3': 'v3','name': 'alex'}
l1 = []
for key in dic:
if 'k' in key:
l1.append(key)
# print(l1)
for key in l1:
del dic[key]
print(dic)