在列表中找到空值差距并分配一组字符串

时间:2016-01-31 20:49:13

标签: python

我是Python新手,我正在寻找一种优雅的方法:

list0 = ["text1","text2","","","text3","","text4","text5","","text6"]

我想将在索引2和3中的间隙之后检测到的非空字符串组合在一起,并从特定索引(例如索引5)开始分配该组。新列表应该看起来像 list1 。 (要查看 list1 click here:

3 个答案:

答案 0 :(得分:1)

好吧,我不确定这是否能回复你的帖子

import Queue
list0 = ["text","text","","","text","","text","text","","text"]
queue = Queue.Queue()
count = 0
for i, val in enumerate(list0):
    if  val == "":
       count += 1
    else:
       if count > 1:
           queue.put(i)
       count = 0

index = 5
queue.put(len(list0))
while queue.qsize() > 1:
    begin = queue.get()
    tmp = filter(lambda a: a != "", list0[begin:queue.queue[0]])
    list0[begin:queue.queue[0]] = [""] * (queue.queue[0]-begin)
    list0[index:index+len(tmp)] = tmp

我只是浏览列表并在间隙之间按块进行排序

['text', 'text', '', '', '', 'text', 'text', 'text', 'text', '']

好吧,我想知道我是不对。

答案 1 :(得分:0)

如果它遗失了什么告诉我

list0 = ["text","text","","","text","","text","text","","text"]
    list1 = list0[:]
    counter= 0
    for i in range(0,len(list0)):
        if(list0[i]=="" and counter < 2 ):
            counter= counter + 1

        elif(counter >= 2):
            list1[i] = "text"

        elif(counter < 2):
            list1[i] = list0[i]

答案 2 :(得分:0)

从问题的描述来看,这似乎是你想要的,但我不确定为什么在你的样本输出的末尾有一个空字符串。

此外,这会直接修改list0,因此如果您愿意,可以随意更改对list1的引用。

list0 = ["text","text","","","text","","text","text","","text"]

# Find the "gap" - the first consectutive empty strings
# gap_pos remains 0 if no gap is found
gap_pos = 0
gap_size = 2
for i in range(len(list0)-gap_size):
    if all(x == '' for x in  list0[i:i+gap_size]):
        gap_pos = i+1
        break # remove this if you want the last gap

# Find the non-empty strings that are detected after the gap
after_gap = filter(lambda x : x != '', list0[gap_pos+1:])

# allocate this group starting at a specific index (e.g. index 5)
specific_index = 5
for i in range(len(after_gap)):
    allocate_at = i + specific_index
    # Make sure not to go out-of-bounds
    if allocate_at < len(list0):
        list0[allocate_at] = after_gap[i]

<强>输出

['text', 'text', '', '', 'text', 'text', 'text', 'text', 'text', 'text']