请查找列表arr = [4, 2, 1, 0, 6, 2, 1]中重复存在的元素,并输出元素的索引
时间: 2023-10-23 08:14:39 浏览: 27
可以通过遍历列表,使用字典记录每个元素出现的次数,然后再遍历一次字典,输出出现次数大于1的元素及其索引。代码如下:
```python
arr = [4, 2, 1, 0, 6, 2, 1]
count_dict = {}
for i, num in enumerate(arr):
if num not in count_dict:
count_dict[num] = 1
else:
count_dict[num] += 1
for num, count in count_dict.items():
if count > 1:
print(f"元素 {num} 重复存在,索引为:", end="")
for i, n in enumerate(arr):
if n == num:
print(i, end=" ")
print()
```
输出结果为:
```
元素 2 重复存在,索引为:1 5
元素 1 重复存在,索引为:2 6
```
相关问题
请查找列表arr = [4, 2, 1, 0, 6, 2, 1]中重复存在的元素,并输出元素的索引,不使用字典的方法
可以使用双重循环遍历列表,找到相同的元素并记录它们的索引。具体实现如下:
```python
arr = [4, 2, 1, 0, 6, 2, 1]
duplicates = []
for i in range(len(arr)):
for j in range(i+1, len(arr)):
if arr[i] == arr[j] and arr[i] not in duplicates:
duplicates.append(arr[i])
print(f"重复元素 {arr[i]} 的索引为 {i} 和 {j}")
```
输出结果为:
```
重复元素 2 的索引为 1 和 5
重复元素 1 的索引为 2 和 6
```
请查找列表arr = [4, 2, 1, 0, 6, 2, 1]中重复存在的元素,并输出元素的索引,不使用字典的方法
可以使用双重循环来解决该问题,外层循环从第一个元素开始,内层循环从外层循环的下一个元素开始遍历,如果有相同的元素,则输出它的索引。
代码如下:
```python
arr = [4, 2, 1, 0, 6, 2, 1]
for i in range(len(arr)):
for j in range(i+1, len(arr)):
if arr[i] == arr[j]:
print("重复元素为:", arr[i], "索引分别为:", i, j)
```
输出结果为:
```
重复元素为: 2 索引分别为: 1 5
重复元素为: 1 索引分别为: 2 6
```
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)