为了账号安全,请及时绑定邮箱和手机立即绑定

重复列表中项目的索引

重复列表中项目的索引

紫衣仙女 2021-11-30 15:47:42
我的索引有问题我有一个如下所示的列表:['Persian', 'League', 'is', 'the', 'largest', 'sport', 'event', 'dedicated', 'to', 'the', 'deprived', 'areas', 'of', 'Iran', 'Persian', 'League', 'promotes', 'peace', 'and', 'friendship', 'video', 'was', 'captured', 'by', 'one', 'of', 'our', 'heroes', 'who', 'wishes', 'peace']我想要大写名称的打印索引和大写名称如下所示:0:Persian1:League13:Iran14:Persian15:League但我不能像下面这样打印 reapet 索引:0:Persian 1:League13:Iran0:Persian   <=======1:League    <=======请帮帮我伙计们!
查看完整描述

3 回答

?
侃侃尔雅

TA贡献1801条经验 获得超15个赞

返回格式化字符串的最短理解:

["{}:{}".format(*x) for x in enumerate(lst) if x[1].istitle()]


查看完整回答
反对 回复 2021-11-30
?
牛魔王的故事

TA贡献1830条经验 获得超3个赞

这是因为列表index()返回列表中第一次出现的索引。因此,无论Persian'列表中有多少个,都只会获取第一个'Persian'的索引。


使用enumerate遍历列表跟踪指数的,我会建议一个字典创建,所以你可以进一步使用它:


lst = ['Persian', 'League', 'is', 'the', 'largest', 'sport', 'event', 'dedicated', 'to', 'the', 'deprived', 'areas', 'of', 'Iran', 'Persian', 'League', 'promotes', 'peace', 'and', 'friendship', 'video', 'was', 'captured', 'by', 'one', 'of', 'our', 'heroes', 'who', 'wishes', 'peace']


output = {i: x for i, x in enumerate(lst) if x.istitle()}

# {0: 'Persian', 1: 'League', 13: 'Iran', 14: 'Persian', 15: 'League'}


查看完整回答
反对 回复 2021-11-30
?
FFIVE

TA贡献1797条经验 获得超6个赞

为此,您必须使用列表理解:


[(i, word) for i, word in enumerate(l) if word.istitle()]

>> [(0, 'Persian'), (1, 'League'), (13, 'Iran'), (14, 'Persian'), (15, 'League')]

该函数istitle()检查单词的第一个字母是否以大写开头。


或者你可以使用:


for i, word in enumerate(l):

    if word.istitle():

        print(i,': ', word)


0 :  Persian

1 :  League

13 :  Iran

14 :  Persian

15 :  League


查看完整回答
反对 回复 2021-11-30
  • 3 回答
  • 0 关注
  • 140 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信