|
|
发表于 2018-4-26 19:47:02
|
显示全部楼层
本帖最后由 ABC23 于 2018-4-26 19:49 编辑
list3 = [name + ':' + slogan[2:] for slogan in list1 for name in list2 if slogan[0] == name[0]]
===========================================================
简单的列表推导式。
>>> lyst1 = [1,2,3]
>>> lyst2 = ['a', 'b', 'c']
>>> lyst3 = [str(num)+":"+alp for num in lyst1 for alp in lyst2]
>>> lyst3
['1:a', '1:b', '1:c', '2:a', '2:b', '2:c', '3:a', '3:b', '3:c']
lyst3 = [str(num)+":"+alp for num in lyst1 for alp in lyst2
这等价于如下代码:
lyst3 = []
for num in lyst1:
for alp in lyst2:
lyst3.append(str(num)+':'+alp)
--------------------------
如果是[:x]代表切片(slice操作),if条件判断:
看一个好玩的例子
>>> lyst1 = ['王大海', '李铁蛋', '刘二狗', '洪双喜']
>>> lyst2 = ['@bcd', '@fgh', '#iop', '!jko']
>>> lyst3 = [name+code[1:].upper() for name in lyst1 for code in lyst2 if code.startswith('@')]
>>> for item in lyst3:
print(item)
王大海BCD
王大海FGH
李铁蛋BCD
李铁蛋FGH
刘二狗BCD
刘二狗FGH
洪双喜BCD
洪双喜FGH |
|