【每日一题0625】依次输出姓名与性别组合

user=['user1','user2','user3']
sex=['男','女','男']
#输出
[
    {'user': 'user1', 'sex': '男'},
    {'user': 'user2', 'sex': '女'},
    {'user': 'user3', 'sex': '男'}
]
def name_and_sex(user: list, sex: list):
    """依次输出姓名和性别"""
    # user = ['user1', 'user2', 'user3']
    # sex = ['男', '女', '男']
    if len(user) != len(sex):
        return False
    else:
        return [{'user': user[i], 'sex': sex[i]} for i in range(len(user))]

day day up 输出组合

user=[‘user1’,‘user2’,‘user3’]
sex=[‘男’,‘女’,‘男’]
#输出 [ {‘user’: ‘user1’, ‘sex’: ‘男’}, {‘user’: ‘user2’, ‘sex’: ‘女’}, {‘user’: ‘user3’, ‘sex’: ‘男’} ]
list1=
for k,v in zip(user, sex):
dict1={}
dict1[“user”]=k
dict[“sex”]=v

list1.append(dict1)

print(list1)

user=[‘user1’,‘user2’,‘user3’]
sex=[‘男’,‘女’,‘男’]
list =
for i in range(3):
dict = {‘user’:user[i], ‘sex’:sex[i]}
list.append(dict)
print(list)

user = [‘user1’, ‘user2’, ‘user3’]
sex = [‘男’, ‘女’, ‘男’]
new_info_list =
for item in (zip(user, sex)):
data = {“user”: item[0], “sex”: item[1]}
new_info_list.append(data)

print(new_info_list)

user=[‘user1’,‘user2’,‘user3’]
sex=[‘男’, ‘女’, ‘男’]
#方法一,循环遍历
userList =
for i in range(3):
dicts = {‘user’:user[i],‘sex’:sex[i]}
userList.append(dicts)
return userList
#方法二
#使用zip内置函数,传入可迭代的数据,例如列表,返回一个元组
for i in zip(user,sex):
dicts={‘user’:i[0],‘sex’:i[1]}
userList.append(dicts)
return userList

题解

user=['user1','user2','user3']
sex=['男','女','男']

def fn():
    return [{'user':u, 'sex': s} for u,s in zip(user, sex)]

assert fn() == [{'user': 'user1', 'sex': '男'},{'user': 'user2', 'sex': '女'},{'user': 'user3', 'sex': '男'}]

:partying_face: :partying_face: :partying_face: :partying_face: :partying_face: :partying_face:

def group(user:list,sex:list) ->list:
    return [{'user':i,"sex":j} for (i,j) in zip(user,sex) ]

关闭