簡體   English   中英

檢查Python列表中的下一個對象

[英]Checking the next object in Python list

我有一個包含以下信息結構的list (來自CSV):

Item 1
NUMBER Random ID
Item 2
NUMBER Random ID
Item 3
Item 4
Item 5
NUMBER Random ID

我想創建一個新的list (CSV),如下所示:

Item 1 NUMBER Random ID
Item 2 NUMBER Random ID
Item 5 NUMBER Random ID

因此,如果下一行不包含字符串NUMBER ,那么我想從Item 1,2,3...及其下一行創建一個字符串。

我可以讀取CSV並將其用作列表,但是我不知道如何跟蹤行。 我的第一個想法是創建一個字典列表,其中每個字典都包含該行及其內容的索引號,然后我可以遍歷list_with_dicts並檢查原始列表的下一行。

raw_list = [] 
num = 0
list_with_dicts = []
for x in raw_list:

    num2 = num + 1
    dict1 = {}
    dict1['index'] = num2
    dict1['çontent'] = x 
    list_with_dicts.append(dict1)

for d in list_with_dicts:

    number_of_next_line = d['index'] + 1    

    if "NUMBER" in raw_list[number_of_next_line]:
        new_string = "%s %s" % (d[content], raw_list[number_of_next_line])
    else:
        print("String without number")

但是我不確定這是最簡單,最好的方法,因此如果有人可以向我展示一個更簡單的解決方法,我將不勝感激。

好玩的問題!

raw_list = ["Item 1",
            "NUMBER Random ID1",
            "Item 2",
            "NUMBER Random ID2",
            "Item 3",
            "Item 4",
            "Item 5",
            "NUMBER Random ID5"]

clean_list = [raw_list[i]+" "+raw_list[i+1] for i in range(0,len(raw_list),2) if "Item" not in raw_list[i+1]]
print clean_list

輸出:

['Item 1 NUMBER Random ID1', 'Item 2 NUMBER Random ID2', 'Item 5 NUMBER Random ID5']

您還可以使用zip使其更短,但可讀性可能更低:

clean_list1 = [i1+" "+i2 for i1,i2 in zip(raw_list[::2],raw_list[1::2]) if "Item" not in i2]
print clean_list1

這個問題的處理方法略有不同-搜索包含字符串NUMBER ,然后將該行與上一行連接。 這將產生更簡單的代碼:

l = ['Item 1', 'NUMBER Random ID', 'Item 2', 'NUMBER Random ID', 'Item 3', 'Item 4', 'Item 5', 'NUMBER Random ID']

result = []
for i, s in enumerate(l[1:], 1):
    if 'NUMBER' in s:
       result.append('{} {}'.format(l[i-1], s))

或作為列表理解:

result = ['{} {}'.format(l[i-1], s) for i,s in enumerate(l[1:], 1) if 'NUMBER' in s]

目前尚不清楚期望輸出什么-您提到CSV,這表示輸出列表應包含單個字段,在這種情況下,結果應為列表列表。 像這樣:

result = [[l[i-1], s] for i,s in enumerate(l[1:], 1) if 'NUMBER' in s]

這將創建以下列表列表:

[['Item 1', 'NUMBER Random ID'],
 ['Item 2', 'NUMBER Random ID'],
 ['Item 5', 'NUMBER Random ID']]

可以使用csv模塊輕松將其保存到CSV文件中:

import csv

with open('result.csv', 'w') as f:
    csv.writer(f).writerows(result)

使用enumerate(<list>)可以迭代索引和元素,因此可以輕松檢查下一個元素:

result = []
for i, val in enumerate(lst):
    if i == len(lst) - 1:
        break # to avoid IndexError
    if lst[i + 1][:3] == 'NUM':
        result.append('%s %s' % (val, lst[i + 1])

功能編程版本:

result = \
    list(
        map(
            lambda i: 
                 '%s %s' % (lst[i - 1], lst[i]),
            filter(
                lambda i:
                    lst[i][:3] == 'NUM',
                range(1, len(lst))
            )
        )
    )

使用列表理解:

result = ["%s %s" % (x,raw_list[i+1]) for i, x in enumerate(raw_list) 
                if i < len(raw_list)-1 and 'NUMBER' in raw_list[i+1]]
new_list=[]
i=0
while i < len(raw_list)-1:
    if raw_list[i+1][:len("NUMBER")] == "NUMBER":
        new_list.append("%s %s" % (raw_list[i], raw_list[i+1]))
        i=i+2
    else:
        i=i+1
result = []
i, l = 0, len(raw_input)
while i < l:
  if 'item' in raw_input[i]:
    result.append(raw_input[i])
  else:
    result[-1] += raw_input[i]
  i += 1
return filter(lambda x: 'random' in x.lower(), result)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM