在某一点将列表分成更小的列表
Breaking a list into smaller lists at a point
我写了一个函数,例如 [["a",1],["b",2],["a",2],["b",3]],其中每个小列表都有一个字母和一个数字,以及 returns、[["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]]
我写的任何东西都无法做到这一点。这是一种简单的挑战,没有列表理解,也没有什么可以导入
通常希望您先 post 您的解决方案,但似乎您已经尝试了一些事情并需要帮助。对于以后的问题,请确保您包括您的尝试,因为它可以帮助我们提供更多帮助为什么您的解决方案不起作用,以及其他什么您可以采取的改进解决方案的步骤。
假设您的列表总是以字母或 str
开头,并且所有数字都是 int
类型,您可以使用字典来进行计数。我添加了评论来解释逻辑。
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.Counter
or collections.defaultdict
进行计数,但由于您提到没有导入,因此上述解决方案遵循这一点。
此代码可以帮助您:
# 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()
这段代码可以通过脚本运行一次,但它可以在嵌套函数中转换以按照您正在寻找的方式使用它。
我写了一个函数,例如 [["a",1],["b",2],["a",2],["b",3]],其中每个小列表都有一个字母和一个数字,以及 returns、[["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]]
我写的任何东西都无法做到这一点。这是一种简单的挑战,没有列表理解,也没有什么可以导入
通常希望您先 post 您的解决方案,但似乎您已经尝试了一些事情并需要帮助。对于以后的问题,请确保您包括您的尝试,因为它可以帮助我们提供更多帮助为什么您的解决方案不起作用,以及其他什么您可以采取的改进解决方案的步骤。
假设您的列表总是以字母或 str
开头,并且所有数字都是 int
类型,您可以使用字典来进行计数。我添加了评论来解释逻辑。
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.Counter
or collections.defaultdict
进行计数,但由于您提到没有导入,因此上述解决方案遵循这一点。
此代码可以帮助您:
# 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()
这段代码可以通过脚本运行一次,但它可以在嵌套函数中转换以按照您正在寻找的方式使用它。