【问题标题】:Breaking a list into smaller lists at a point在某个点将列表分解为更小的列表
【发布时间】:2020-04-14 22:04:46
【问题描述】:

我编写了一个函数,例如 [["a",1],["b",2],["a",2],["b",3]],其中每个小list 有一个字母和一个数字,并返回 [["a",1,2,"b",2,3]]。

这个问题还有很多,但为了简单起见,下一步就是把它变成一个形式 [["a",3],["b",5]]。每个较小列表的第二项是字母之间的数字之和,即 1,2 与“a”相关联,2,3 与“b”相关联,如原始列表所示。一个字母出现的次数是无限的。

另一个例子总结一下:function([["a",1,3,4,"b",2,2,"c",4,5]]) => [["a",8] ,["b",4],["c",9]]

我写的任何东西都没有接近完成这一点。这是一种简单的挑战,没有列表理解,也无法导入任何内容

【问题讨论】:

  • 通常希望发布您尝试过的代码以及它如何未能按照您的意愿进行操作。请在您的问题中发布该信息......并使用代码格式使其可读。
  • 列表的原始格式更易于处理。 for k, v in original: d[k] += v,其中d = collections.defaultdict(int)

标签: python python-3.x for-loop nested-lists


【解决方案1】:

这段代码可以帮助你:

# Assuming a random initial list:
data = [["a",1,3,4,4,2,"b",2,2,3,5,2,3,"c",4,3,5,5]]
# An empty list where it will be added the result:
new_data = []
# Variable to accumulate the sum of every letter:
sume = 0

# FOR loop to scan the "data" variable:
for i in data[0]:
    # If type of the i variable is string, we assume it's a letter:
    if type(i) == str:
        # Add accumulated sum
        new_data.append(sume)
        # We restart *sume* variable:
        sume = 0
        # We add a new letter read:
        new_data.append(i)
    else:
        # We accumulate the sum of each letter:
        sume += i

# We extract the 0 added initially and added the last sum:
new_data = new_data[1::]+[sume]

# Finally, separate values in pairs with a FOR loop and add it to "new_data2":
new_data2 = []
for i in range(len(new_data)//2):
    pos1 = i*2
    pos2 = pos1+1
    new_data2.append([new_data[pos1],new_data[pos2]])

# Print data and new_data2 to verify results:
print (data)
print (new_data2)
# Pause the script:
input()

此代码可以通过脚本运行一次,但它可以转换为嵌套函数以按照您的方式使用它。

【讨论】:

    【解决方案2】:

    通常希望您先发布解决方案,但您似乎已经尝试了一些方法并需要帮助。对于未来的问题,请确保您包括您的尝试,因为它可以帮助我们提供更多帮助,了解为什么您的解决方案不起作用,以及您可以采取哪些其他步骤来改进你的解决方案。

    假设您的列表始终以字母或str 开头,并且所有数字都是int 类型,您可以使用字典进行计数。我添加了 cmets 来解释逻辑。

    def group_consecutive(lst):
        groups = {}
    
        key = None
        for item in lst:
    
            # If we found a string, set the key and continue to next iteration immediately
            if isinstance(item, str):
                key = item
                continue
    
            # Add item to counts
            # Using dict.get() to initialize to 0 if ket doesn't exist
            groups[key] = groups.get(key, 0) + item
    
        # Replacing list comprehension: [[k, v] for k, v in groups.items()]
        result = []
        for k, v in groups.items():
            result.append([k, v])
    
        return result
    

    然后你可以这样调用函数:

    >>> group_consecutive(["a",1,3,4,"b",2,2,"c",4,5])
    [['a', 8], ['b', 4], ['c', 9]]
    

    更好的解决方案可能会使用collections.Countercollections.defaultdict 进行计数,但由于您提到没有导入,所以上述解决方案坚持这一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-09
      • 1970-01-01
      • 2016-12-04
      • 2018-10-20
      相关资源
      最近更新 更多