由于我是python编程的新手,我在编写python程序时遇到了困难。我试图在长列表中计算一组七个对象(?)的三个编号数字和选项卡。然后我需要找到哪一组数字(三个数字的倍数)具有列表中的最大数字。这些数字由一个标签分隔,数字组合在七个以上。例如:
['128','130','140','145','','','','283','379','','','','','','175','183','187','','','',''etc.]
列表中的第一组数字和标签是128,130,140,145,标签,标签,标签。列表中的第二组数字和选项卡是283,379,选项卡,选项卡,选项卡,选项卡,选项卡。最后,列表中的第三组数字是175,183,187,制表符,制表符,制表符,制表符。
我想计算七组数字和标签中的三位数,然后有一个最大输出数,其中哪一组显示最多三位数字。例如:
['128','130','140','145','','','','283','379','','','','','','175','183','187','','','','']
this first set = 4 this second set = 2 this third set = 3
在此示例中,最终输出编号应为4,因为第一组七个对象显示最多3位数字。这是我现在拥有的东西。
#!/usr/bin/env python
allele = '128 130 140 145 283 379 175 183 187
elementlist=allele.split('\t')
string= str(elementlist)
type = string.replace('\t','0')
print type
我很感激任何想法或担忧。
答案 0 :(得分:0)
只是草图:
>>> L = ['128','130','140','145','','','','283','379','','','','','','175','183','187','','','','']
子群:
>>> L1 = [L[i : i+7] for i in range(0, len(L), 7)]
>>> L1
[['128', '130', '140', '145', '', '', ''],
['283', '379', '', '', '', '', ''],
['175', '183', '187', '', '', '', '']]
子组中的元素:
>>> L2 = [sum(x.isdigit() for x in SL) for SL in L1]
>>> L2
[4, 2, 3]
最大:
>>> max(L2)
4
答案 1 :(得分:0)
如果您需要的只是最长的段,您可能只想保留对最长段的起点和长度的引用,因为这样可以避免复制许多不需要的元素。记忆。这对于非常大的数据结构非常有用。在这种情况下,您可能希望使用以下内容:
def longest_segment(target_list, empty_element):
longest_start = longest_len = 0
current_start = current_len = 0
i=0
for element in target_list:
if element == empty_element:
current_start = -1
current_len = 0
else:
if(current_start == -1):
current_start = i
current_len = current_len + 1
if( current_len > longest_len ):
longest_start = current_start
longest_len = current_len
i = i + 1
return longest_start,longest_len
用法示例:
L = ['128','130','140','145','','','','283','379',
'','','','','','175','183','187','','','','']
#The function supports a generic empty element so you could use other separators, like tab
start, size = longest_segment(L,'')
print ("The longest segment starts at:\t" ,start)
print ("The longest segment has length:\t",size )
#Up to this moment, there is no need to copy or keep more elements in memory.
print ("The longest segment is:\t", L[start:start + size])