【问题标题】:How to write an indexed loop over a list in Python?如何在 Python 中的列表上编写索引循环?
【发布时间】:2023-04-06 10:23:02
【问题描述】:

我有以下代码,它采用字符串 bios_score 并在拆分后将其转换为字符串 ('b')。所需的输出是生成我在下面手动构建的内容(具有相应分数的用户列表)

我会对构建 for 循环以通过列表实现此目的的最有效方法感兴趣。注意:我知道解决此问题的最佳方法是字典,但这些目的我想使用列表。

代码:

biology_score="user1,30,user2,60,user3,99"
print(biology_score[1]) #for testing purposes
b=biology_score.split(",")
print(b) #prints lists
print(b[2]) #prints element in index 2 in the list

#desired output
print(b[0],"scored",b[1])
print(b[2],"scored",b[3])
print(b[4],"scored",b[5])

#create a for loop to do the above

必填答案

  1. 最优雅的解决方案(for循环通过遍历列表产生上述)

  2. 将字符串转换为字典的最简单/最快的方法,使用最少的步骤,然后实现相同的输出(用户:分数)

【问题讨论】:

标签: python list for-loop


【解决方案1】:

我不确定这是否是您要查找的内容:

biology_score="user1,30,user2,60,user3,99"
print(biology_score[1]) #for testing purposes
b=biology_score.split(",")
biology_dict = {}

for i in range(0, len(b), 2):  #looks only at even indices
    print(b[i],"scored",b[i+1])
    biology_dict[b[i]] = b[i+1]

【讨论】:

  • 对不起,忽略之前的评论 - 这很漂亮。工作正常。谢谢!
【解决方案2】:

如果这是你需要的。

#create a for loop to do the above
for i in range(0,len(b)-1,2):
  print(b[i],"scored",b[i+1])

注意:Python 版本 dict 时,订单可能不会保留。

【讨论】:

    【解决方案3】:

    其中一个选项是使用字典

    如果iterables长度不均匀,则用fillvalue填充缺失值

    import itertools    
    d = dict(itertools.zip_longest(*[iter(biology_score.split(","))] * 2, 
    fillvalue=""))
    
    for k, v in d.items():
        print(k,'scored', v)
    

    【讨论】:

    • 能否请您清楚地解释一下 d = dict(itertools.zip_longest(*[iter(biology_score.split(","))] * 2 行,谢谢!
    【解决方案4】:

    您可以使用 itertools 模块中的 grouper 配方:

    import itertools
    def grouper(iterable, n, fillvalue=None):
        "Collect data into fixed-length chunks or blocks"
        # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
        args = [iter(iterable)] * n
        return itertools.zip_longest(*args, fillvalue=fillvalue)
    

    然后:

    for user, score in grouper(b, 2):
        print(user, 'scored', score)
    

    制作字典:

    dictionary = dict(grouper(b, 2))
    for user, score in dictionary.items():
        print(user, 'scored', score)
    

    如果项目的原始顺序应保留,则使用 OrderedDict。

    【讨论】:

      【解决方案5】:

      主要是重写@chngzm 的答案,可能不适合您的教学目的,但使用生成器非常好:

      def user_scores(scores):
        s = scores.split(",")
        for idx in range(0, len(s), 2):
          yield s[idx], s[idx+1]
      
      biology_score="user1,30,user2,60,user3,99"
      
      for user, score in user_scores(biology_score):
        print("{0} scored {1}".format(user, score))
      
      biology_dict = dict(s for s in user_scores(biology_score))
      for user in biology_dict:
        print("{0} scored {1}".format(user, biology_dict[user]))
      

      【讨论】:

        【解决方案6】:

        获得所需结果的一种 Pythonic 方法是使用 zip

        biology_score = "user1,30,user2,60,user3,99"
        values = biology_score.split(',')
        print(dict(zip(values[::2], values[1::2])))
        # {'user2': '60', 'user3': '99', 'user1': '30'}
        

        如果想要整数分数,可以使用map

        print(dict(zip(values[::2], map(int, values[1::2]))))
        # {'user2': 60, 'user3': 99, 'user1': 30}
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-09-07
          • 2014-01-28
          • 1970-01-01
          • 2019-03-03
          相关资源
          最近更新 更多