keys_list = ['A', 'B', 'C']
values_list = ['blue', 'red', 'bold']
有三种方法实现方式:
1.使用Python/ target=_blank class=infotextkey>Python zip、dict函数
dict_method_1 = dict(zip(keys_list, values_list))
print(dict_method_1)
2. 使用带有字典推导式的 zip 函数
dict_method_2 = {key:value for key, value in zip(keys_list, values_list)}
print(dict_method_2)
3.循环使用zip函数
items_tuples = zip(keys_list, values_list)
dict_method_3 = {}
for key, value in items_tuples:
if key in dict_method_3:
pass
else:
dict_method_3[key] = value
print(dict_method_3)
运行结果:
{'A': 'blue', 'B': 'red', 'C': 'bold'}
当有两个或更多列表时,想要将它们全部收集到一个大列表中,其中小列表的所有第一项构成较大列表中的第一个列表
例如:有 4 个列表 [1,2,3]、['a','b','c']、['h','e','y']、[4,5,6]
要为这四个列表创建一个新列表 [[1,'a','h',4], [2,'b','e',5], [3,'c','y',6]]
def merge(*args, missing_val = None):
max_length = max([len(lst) for lst in args])
outList = []
for i in range(max_length):
outList.Append([args[k][i] if i < len(args[k]) else missing_val for k in range(len(args))])
return outList
merge([1,2,3],['a','b','c'],['h','e','y'],[4,5,6])
import operator
people = [
{
'name': 'John',
"age": 64
},
{
'name': 'J.NET',
"age": 34
},
{
'name': 'Ed',
"age": 24
},
{
'name': 'Sara',
"age": 64
},
{
'name': 'John',
"age": 32
},
{
'name': 'Jane',
"age": 34
},
{
'name': 'John',
"age": 99
},
]
people.sort(key=operator.itemgetter('age'))
print(people)
people.sort(key=operator.itemgetter('name'))
print(people)
运行结果:
[{'name': 'Ed', 'age': 24}, {'name': 'John', 'age': 32}, {'name': 'Janet', 'age': 34}, {'name': 'Jane', 'age': 34}, {'name': 'John', 'age': 64}, {'name': 'Sara', 'age': 64}, {'name': 'John', 'age': 99}]
[{'name': 'Ed', 'age': 24}, {'name': 'Jane', 'age': 34}, {'name': 'Janet', 'age': 34}, {'name': 'John', 'age': 32}, {'name': 'John', 'age': 64}, {'name': 'John', 'age': 99}, {'name': 'Sara', 'age': 64}]
列表推导可以在列表填写里代替讨厌的循环,其基本语法为
[ expression for item in list if conditional ]
squares = [x**2 for x in range(10)]
print(squares)
运行结果:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]