【问题标题】:Python How to specify which character to index if there are duplicates如果有重复,Python如何指定要索引的字符
【发布时间】:2018-05-19 21:15:12
【问题描述】:

所以我正在为班级做一个练习,我需要打印出哪些字符出现以及它们出现在哪里。我使用以下代码做到了这一点:

def letterInString(string):
   index = 0
   pos = ""
   stringList = list(string)
   positions = []
   counter = 0
   occurences = {}
   for l in string:
       for x in string:
           if x == l:
               counter += 1
               positions.append(stringList.index(x))
            for item in positions:
                if index == 0:
                    pos = str(positions[index])
                    index += 1
                else:
                    pos = pos + "," + str(positions[index])
                    index += 1
            occurences[l.upper()] = str(counter) + "(" + pos + ")"
            index = 0
            positions = []
        counter = 0
    for key,value in occurences.items():
        print(key + ": " + str(value))

letterInString("hello")

该代码对没有重复的单词工作得很好,但是当有重复时,它不知道要索引哪个字母。我代码的最后一部分只是为了测试某些情况。请帮忙!!!

感谢任何帮助!

【问题讨论】:

  • 你可以这样做[ {"char": i,"position": c} for i,c in enumerate(s)] where s="hello"
  • 对,这基本上就是我的答案

标签: python string list indexing


【解决方案1】:

两种方法:

你可以用 dict 做一些事情:

data='hello'

dict_1={}
for i,j in enumerate(data):
    if j not in dict_1:
        dict_1[j]=[(i,j)]
    else:
        dict_1[j].append((i,j))


for key,value in dict_1.items():
    if len(value)>1:
        print(value)

输出:

[(2, 'l'), (3, 'l')]

第二种使用defaultdict的方法:

import collections

d=collections.defaultdict(list)
for key1,value1 in enumerate(data):
    d[value1].append(key1)

print(d)

print([(key1,value1) for key1,value1 in d.items() if len(value1)>1])

输出:

[('l', [2, 3])]

【讨论】:

    【解决方案2】:

    我认为您的代码可能过于复杂。怎么样

    def analyze(str_):
        data = [(c, str_.count(c), i) for i, c in enumerate(str_)]
        return "\n".join(["{}: count = {}. index = {}".format(*d) for d in data])
    
    print analyze("hello")
    
    # h: count = 1. index = 0
    # e: count = 1. index = 1
    # l: count = 2. index = 2
    # l: count = 2. index = 3
    # o: count = 1. index = 4
    

    请注意列表解析、字符串替换和字符串的count 方法的使用。您可能希望重写此函数以返回不同格式的数据(即不作为字符串)。

    【讨论】:

      猜你喜欢
      • 2014-10-04
      • 2019-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-13
      • 1970-01-01
      • 2018-07-18
      • 1970-01-01
      相关资源
      最近更新 更多