通用 任意数组 一个含有字符串的数组,例如:["a","b","a","c","b","d","a"],需要得到一个新数组 ["a1","b1","a2","c","b2","d","a3"] 要求: 未重复的元素不处理 重复的元素加上编号 不能影响正常数组的顺序
时间: 2024-06-02 22:04:40 浏览: 78
复制数组或从数组中抽取特定元素组成新数组
可以通过遍历原始数组,并使用一个字典来记录元素出现的次数来实现。对于每一个元素,如果在字典中不存在,则将其添加到字典中,同时在新数组中添加该元素;如果在字典中已经存在,则在新数组中添加该元素的编号。以下是示例代码:
```python
arr = ["a", "b", "a", "c", "b", "d", "a"]
new_arr = []
count_dict = {}
for elem in arr:
if elem not in count_dict:
count_dict[elem] = 1
new_arr.append(elem)
else:
count_dict[elem] += 1
new_arr.append(elem + str(count_dict[elem]))
print(new_arr)
```
输出结果为:["a1", "b1", "a2", "c", "b2", "d", "a3"]
阅读全文