如何查找列表中重复项的索引?

如何解决如何查找列表中重复项的索引?

程序的工作原理

  1. 从用户那里获取一个字符串

  2. 如果字符串中有句点或逗号,则删除它

3.split() 将该字符串放入名为 reshte 的列表中。

  1. 从列表中删除第一项。

  2. 取名字为大写字母并带有for loop的项目,然后显示结果。

我想在输出中打印带有索引号的项目,但我不能。

我给程序的输入:

波斯联赛是最大的体育赛事,致力于为 伊朗的贫困地区。波斯联盟促进和平与 友谊。这段视频是由我们的一位英雄拍摄的,他希望 和平。

我的代码:

bs = [',','.']
reshte = input()
for s in bs:
    if s in reshte:
        reshte = reshte.replace(s,'')

reshte = reshte.split()
b = reshte[0]
css = [reshte.remove(b) for k in reshte if b in reshte]


for f in reshte:
    if f[0] == f[0].upper():
       print(f)

这是我代码的输出==错误:

Persian
League
Iran
Persian
League

但我希望输出如下==正确:

2:Persian
3:League
15:Iran
17:Persian
18:League

请帮我解决这个问题

解决方法

只需更改最后一部分即可打印数字:

const DEFAULT_NUMBER_VALUE = 0;
const DEFAULT_PRECISION = 100;

function parseAddInput(input){
  if (!input) {
    return DEFAULT_NUMBER_VALUE;
  }
  
  if (typeof input === 'string'){
    input = parseInt(input);
  }
  
  const roundedNumber = Math.round(input * (10 * DEFAULT_PRECISION));
  
  return roundedNumber;
}

function getSum(a,b){
  return Array(
    parseAddInput(a)
  ).concat(
    Array(parseAddInput(b))
  ).length / 100;
}

function add(number1,number2){
  return getSum(number1,number2);
}
,

问题在于,当您从列表中删除项目时,您输出的单词的索引会发生变化。最简单的做法是之后删除项目,以便在循环中,单词仍保留其原始索引。这样做时,您可以简单地在循环中添加条件 f != b 以过滤掉 reshte[0] 不被打印。

以下代码实现了这一点。请注意,您的代码的第一部分可以大大简化 - 在进行替换之前无需检查 ,. 是否确实出现在字符串中 - replace 是空操作如果文本没有出现在字符串中。

reshte = input()

reshte = reshte.replace(',','').replace('.','')
reshte = reshte.split()

b = reshte[0]

for i,f in enumerate(reshte):
    if f[0] == f[0].upper() and f != b:
        print(f'{i + 1}:{f}')

css = [reshte.remove(b) for k in reshte if b in reshte]
,

我假设索引的结果应该是索引 before 删除列表中的第一个元素(步骤 3)并向索引添加 1,因为结果看起来是我们的索引通常计算,而不是在 Python(或大多数编程语言,请参阅下面的指南)中计算。

我还看到结果中没有“This”这个词,所以我假设您希望 ALSO 跳过所有以大写开头且与第一个元素相同的词列表,所以单词“The”。

1.使用列表作为结果

test_string = """The Persian League is the largest sport event dedicated,\
to the deprived,areas of Iran. The Persian League promotes,peace and friendship.  
This video was captured by one of our heroes,who wishes peace.
"""

bs = [','.']
result_2 = []
# ========== < REMOVE COMMAS AND DOTS > ========= #
for punct in bs:
    if punct in test_string:
        test_string = test_string.replace(punct,'')


# ========== < STORE FIRST ELEMENT AT INDEX 0 > ========= #
reshte = test_string.split()
first_element = reshte[0]


# ========== < COUNTS ELEMENTS IN LIST > ========= #
results = []
for idx,f in enumerate(reshte):
    if first_element[0] == f[0]: # NOTE: we don't remove the first element but only skipping it all in once
        continue
    if f[0].isupper():
        results.append((idx,f))

for idx,value in results:
    print(f'{idx+1}:{value}')

# 2:Persian
# 3:League
# 15:Iran
# 17:Persian
# 18:League

2.使用字典

results = dict()
for idx,f in enumerate(reshte):
    if first_element[0] == f[0]: # NOTE: we don't remove the first element
        continue
    if f[0].isupper():
        results[idx] = f

for key,value in results.items():
    print(f'{key+1}:{value}')
    
# 2:Persian
# 3:League
# 15:Iran
# 17:Persian
# 18:League

print(results)

# {1: 'Persian',2: 'League',14: 'Iran',16: 'Persian',17: 'League'}

3.计数重复的列表

# ========== < FIND UNIQUE ELEMENT IN LIST > ========= #
unique_string = {string for string in reshte if string[0].isupper()}
results = []
# ========== < COUNT ELEMENTS  > ========= #
for element in unique_string:
    if first_element[0] == element[0]:
        continue
    element_count = reshte.count(element)
    results.append((element_count,element))

for idx,value in results:
    print(f'{idx}:{value}')
# 1: Iran
# 2: League
# 2: Persian

4.使用计数器

from collections import Counter

counted = Counter(reshte)

for element,count in counted.items():
    if element[0] == first_element[0]:
        continue
    elif element[0].isupper():
        print(f'{count}:{element}')
        
# 2:Persian
# 2:League
# 1:Iran

指南和文档

堆栈溢出相关问题

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-