我會盡力解釋。
說我有這個;它代表一個用戶名(例如:jjo)、一個可選的真實姓名(例如:josh),并且后面總是跟一個“洗掉”。
list_of_people = ['jjo','josh','remove','flor30','florentina','remove','mary_h','remove','jasoncel3','jason celora','remove', 'lashit', 'remove']
我的目標是實作這一目標:
cut_list = [ ['jjo','josh'], ['flor30', 'florentina'], ['mary_h'], ['jasoncel3', 'jason celora'], ['lashit']]
這里的問題是真實姓名是可選的,因此,它并不總是完美的“三重奏”。換句話說,我需要使用“洗掉”的存在作為支點來削減我的清單。
從口頭上講,我會說代碼是:
如果遇到“洗掉”,請倒退并存盤所有內容,直到遇到另一個“洗掉”
一個問題是一開始沒有“洗掉”(盡管我可以手動添加它),但我的主要問題是邏輯。我做錯了。
這是迄今為止我的“最佳”鏡頭及其給出的結果:
list_of_people = ['jjo','josh','remove','flor30','florentina','remove','mary_h','remove','jasoncel3','jason celora','remove', 'lashit', 'remove']
#Add the first 2 items
#If "remove" is there (means there was no real name), remove it
#Turn list into a list of lists
cut_list = list_of_people[0:2]
if "remove" in cut_list:
cut_list.remove("remove")
cut_list = [cut_list]
#Loop through and cut based on the presence of "remove"
for i in range(2, len(list_of_people)):
if list_of_people[i] == 'remove':
first_back = list_of_people[i-1]
if list_of_people.append(list_of_people[i-2]) != 'remove':
second_back = list_of_people[i-2]
cut_list.append([first_back, second_back])
print(cut_list)
# #Should give:
# ##cut_list = [ ['jjo','josh'], ['flor30', 'florentina'], ['mary_h'], ['jasoncel3', 'jason celora'], ['lashit']]
[['jjo', 'josh'], ['josh', 'jjo'], ['josh', 'jjo'], ['josh', 'jjo'], ['florentina', 'flor30'] , ['florentina', 'flor30'], ['mary_h', 'remove'], ['mary_h', 'remove'], ['mary_h', 'remove'], ['jason celora', 'jasoncel3' ], ['jason celora', 'jasoncel3'], ['lashit', 'remove']]
uj5u.com熱心網友回復:
我選擇保持這個簡單,并使用”remove”作為標記在串列中迭代一次以進行額外的處理。
list_of_people = ['jjo','josh','remove','flor30','florentina','remove','mary_h','remove','jasoncel3','jason celora','remove', 'lashit', 'remove']
result = []
user = []
for name in list_of_people:
if name != "remove":
# Add to the people list
user.append(name)
else:
# Found a remove, reset `user` after adding to result
result.append(user)
user = []
print(result)
uj5u.com熱心網友回復:
from itertools import groupby
sentence = ['jjo', 'josh', 'remove', 'flor30', 'florentina', 'remove', 'mary_h',
'remove', 'jasoncel3', 'jason celora', 'remove', 'lashit', 'remove']
i = (list(g) for _, g in groupby(sentence, key='remove'.__ne__))
l = [a b for a, b in zip(i, i)]
N = 'remove'
res = [[ele for ele in sub if ele != N] for sub in l]
print(res)
uj5u.com熱心網友回復:
嘗試:
from itertools import groupby
out = [
list(g) for v, g in groupby(list_of_people, lambda x: x != "remove") if v
]
print(out)
印刷:
[['jjo', 'josh'], ['flor30', 'florentina'], ['mary_h'], ['jasoncel3', 'jason celora'], ['lashit']]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/510292.html
標籤:Python细绳列表
