繁体   English   中英

根据下一个元组的长度加入列表中的元组

[英]Join tuples in list based on length of next tuple

例如,我有一个包含许多不同长度的元组的列表,例如

list_with_length_of_tuples = [2000, 2000, 1700, 300, 299, 1699, 2000, 2000, 300, 200, 1499]

所以我想得到一个列表,它将长度小于 2000 的元组连接在一起。 为了得到一个想法,我们必须得到以下信息:

list_with_length_of_tuples_1= [2000, 2000, 2000, 2000, 1998, 2000, 2000, 1999]

它看起来很奇怪,这不是一项微不足道的任务,但我的想法是我有一个不同长度的元组列表,但它们都应该等于大约 2000(它可以在大约从 1995 年到 2005 年的范围内),但是有些元组被分成几个部分,它们需要连接在一起以获得大约 2000 的所需长度。困难在于一些元组被分成几个部分,而下一个元组也被分成几个部分。 有没有办法解决这个问题? 我的解释听起来含糊不清,但如果您还有其他澄清问题,请提出。

如果计算时间不是问题,则将所有内容转换为列表,然后使用简单的 foo 循环。

#T=[some tuples with the above length]
tmp=[]
for t in T:
    if not tmp or len(tmp[-1])+len(t)>2000:
        tmp.append(list(t))
    else:
        tmp[-1]+=t
result=[tuple(t) for t in tmp]

更有效地,首先处理长度:

list_with_length_of_tuples = [2000, 2000, 1700, 300, 299, 1699, 2000, 2000, 300, 200, 1499]
#T=[some tuples with the above length]
tmp=[]
for i,v in enumerate(list_with_length_of_tuples):
    if not tmp or tmp[-1][1]+v>2000:
        tmp.append([[i],v])
    else:
        tmp[-1]=tmp[-1][0]+[i],tmp[-1][1]+v
result=[]
for ndxx, _ in tmp:
    result.append[(z for n in ndxx for z in T[n])]
# O(nc) time complexity where n is length of list and c is the max length of chunks
def form_correct_tuples(ls):
    correct_length = []
    number_of_parts = 0
    
    for idx, val in enumerate(ls):
        if number_of_parts > 1:
            number_of_parts -= 1
            if val != 2000:
                continue
        
        if 1995 <= val <= 2005:
            correct_length.append(val)
        else:
            sum_ = 0
            while sum_ < 1995 or sum_ > 2005:
                sum_ += ls[idx]
                idx += 1
                number_of_parts += 1

            correct_length.append(sum_)

    return correct_length

此代码首先检查当前数字是否在 1995 年和 2005 年之间。 如果是,则将其添加到新列表中,否则创建临时sum_变量并将每个部分添加到其中sum_在 1995 年至 2005 年之间达到。最后,在每次迭代中,您检查列表中是否有任何部分不是 go 通过它们再次使用number_of_parts变量。 用你当前的输入测试它:

result = form_correct_tuples(list_with_length_of_tuples)
# -> [2000, 2000, 2000, 1998, 2000, 2000, 1999]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM