Python 在某一点将列表拆分为较小的列表
我编写了一个函数,它以[[“a”,1],“b”,2],“a”,2],“b”,3]]为例,其中每个小列表都有一个字母和一个数字,并返回[[“a”,1,2,“b”,2,3]] 这个问题还有很多,但为了使事情简单化,下一步是将其转换为一种形式[[“a”,3],“b”,5]]。每个较小列表的第二项是字母之间的数字总和,即1,2与“a”关联,2,3与“b”关联,如原始列表所示。字母的出现次数是无限的 另一个要总结的例子:函数([[“a”,1,3,4,“b”,2,2,“c”,4,5]])=>[[“a”,8],“b”,4],“c”,9]]Python 在某一点将列表拆分为较小的列表,python,python-3.x,for-loop,nested-lists,Python,Python 3.x,For Loop,Nested Lists,我编写了一个函数,它以[[“a”,1],“b”,2],“a”,2],“b”,3]]为例,其中每个小列表都有一个字母和一个数字,并返回[[“a”,1,2,“b”,2,3]] 这个问题还有很多,但为了使事情简单化,下一步是将其转换为一种形式[[“a”,3],“b”,5]]。每个较小列表的第二项是字母之间的数字总和,即1,2与“a”关联,2,3与“b”关联,如原始列表所示。字母的出现次数是无限的 另一个要总结的例子:函数([[“a”,1,3,4,“b”,2,2,“c”,4,5]])=>[[“a”,8]
我所写的任何东西都无法实现这一点。这是一种赤裸裸的挑战,没有列表理解,也无法导入任何内容通常希望您先发布解决方案,但似乎您已经尝试了一些方法,需要帮助。对于未来的问题,请确保包括您的尝试,因为这有助于我们提供更多帮助,以了解您的解决方案不起作用的原因,以及您可以采取哪些其他步骤来改进您的解决方案 假设您的列表总是以字母或
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]]
一个更好的解决方案可能会使用或来进行计数,但由于您提到没有导入,因此上述解决方案将遵循这一点 通常希望您先发布解决方案,但似乎您已经尝试了一些方法,需要帮助。对于未来的问题,请确保包括您的尝试,因为这有助于我们提供更多帮助,以了解您的解决方案不起作用的原因,以及您可以采取哪些其他步骤来改进您的解决方案 假设您的列表总是以字母或
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]]
一个更好的解决方案可能会使用或来进行计数,但由于您提到没有导入,因此上述解决方案将遵循这一点 此代码可以帮助您:
#Assuming a random initial list:
data = [["a",1,3,4,4,2,"b",2,2,3,5,2,3,"c",4,3,5,5]]
#A empty list where it will be added the result:
new_data = []
#variable to acumulate the sum of every letter:
sume = 0
#FOR loop to scan "data" variable:
for i in data[0]:
#if type of i variable is string, we assuming it's a letter:
if type(i) == str:
#add accumulated sum
new_data.append(sume)
#we restart *sume* variable:
sume = 0
#we add new letter read:
new_data.append(i)
else:
#we acumulate 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()
此代码可以通过脚本工作一次,但它可以在嵌套函数中转换,以您所寻找的方式使用它。此代码可以帮助您:
#Assuming a random initial list:
data = [["a",1,3,4,4,2,"b",2,2,3,5,2,3,"c",4,3,5,5]]
#A empty list where it will be added the result:
new_data = []
#variable to acumulate the sum of every letter:
sume = 0
#FOR loop to scan "data" variable:
for i in data[0]:
#if type of i variable is string, we assuming it's a letter:
if type(i) == str:
#add accumulated sum
new_data.append(sume)
#we restart *sume* variable:
sume = 0
#we add new letter read:
new_data.append(i)
else:
#we acumulate 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()
此代码可以通过脚本工作一次,但它可以在嵌套函数中转换,以您正在寻找的方式使用它。通常需要一个人发布您尝试过的代码以及它如何失败。请在你的问题中发布这些信息。。。并使用代码格式使其可读。列表的原始格式更易于处理<代码>对于k,v在原文中为:d[k]+=v,其中
d=collections.defaultdict(int)
通常期望有人发布您尝试过的代码,以及它是如何失败的。请在你的问题中发布这些信息。。。并使用代码格式使其可读。列表的原始格式更易于处理<代码>用于k,v原件:d[k]+=v,其中d=collections.defaultdict(int)