|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 ahluo 于 2020-7-28 14:09 编辑
https://fishc.com.cn/forum.php?m ... peid%26typeid%3D398
在这个课后题中,是这样说的:
list1=['1.Just do it', '2.Everything is possible','3.Programme changes the world', '4.Impossible is nothing']
list2=['4.阿迪达斯', '2.李宁','3.工作室', '1.耐克']
list3 如何写?
要达到的结果是:
['1.耐克:Just do it', '2.李宁:Everything is possible', '3.工作室:Programme changes the world', '4.阿迪达斯:Impossible is nothing']
给出的答案是:
list3 = [name + ':' + slogan[2:] for slogan in list1 for name in list2 if slogan[0] == name[0]]
个人想法
这个答案是用的list1和2中第0个字符来对比,相等就执行程序。但是如果list中有10+个数据的话,那1和10项也会符合这个条件,我就不知道怎么做比较好。
我个人的想法是用 index() 来判断 '.' 在每个元素中的位置L,然后对比 [0,L] 的大小,但是不会写 可能是暂时还没有学到这个阶段吧。希望有高手来说一下谢谢啦~
本帖最后由 Twilight6 于 2020-7-28 14:36 编辑
也可以用 split 切割小数点,然后此时就有两个元素了,直接比较第一位元素即可:
- list1=['20.FishC','1.Just do it', '2.Everything is possible','3.Programme changes the world', '4.Impossible is nothing']
- list2=['4.阿迪达斯', '2.李宁','3.工作室', '1.耐克','20.鱼C']
- temp = [i+':'+j[j.index('.')+1:] for i in list2 for j in list1 if i.split('.',1)[0] == j.split('.',1)[0]]
- print(temp)
复制代码
把 [i+':'+j[j.index('.')+1:] for i in list2 for j in list1 if i.split('.',1)[0] == j.split('.',1)[0]] 展开和甲鱼哥课后练习是一个道理哈:
- temp = []
- for i in list2:
- for j in list1:
- if i.split('.', 1)[0] == j.split('.', 1)[0]:
- temp.append(i + ':' + j[j.index('.') + 1:])
- print(temp)
复制代码
输出结果:
- ['4.阿迪达斯:Impossible is nothing', '2.李宁:Everything is possible', '3.工作室:Programme changes the world', '1.耐克:Just do it', '20.鱼C:FishC']
复制代码
|
|