【问题标题】:Extract elements when a condition is met in different lines and storing them in one当在不同的行中满足条件时提取元素并将它们存储在一个中
【发布时间】:2021-07-12 10:22:49
【问题描述】:
我在列表中有如下元素:
temp_list = ["% Work\n"," Hard\n"," Or\n"," Go\n"," Home\n","%","% Happy Coding","%"]
我想实现这个:
final_list = ["Work Hard Or Go Home","Happy Coding"]
元素中的百分号是两个新行之间的分隔符。
【问题讨论】:
标签:
python
string
list
while-loop
conditional-statements
【解决方案1】:
加入单词然后在%上拆分:
temp_list = ["% Work\n"," Hard\n"," Or\n"," Go\n"," Home\n","%","% Happy Coding","%"]
final_list = []
for line in map(str.strip, "".join(temp_list).split("%")):
if not line:
continue
final_list.append(line.replace("\n", ""))
print(final_list)
打印:
['Work Hard Or Go Home', 'Happy Coding']
【解决方案2】:
您可以使用迭代器map、filter 和一些字符串函数lstrip 和replace 来完成此操作
map 接受一个函数,一个迭代器将该函数应用于每个元素并返回一个新的迭代器
filter 接受一个函数和一个可迭代对象,删除不返回 true 的元素
当它的函数被调用时。
lstrip 删除字符串左侧的空格
replace(a,b) 将字符串中的 a 替换为 b
flat = ""
# Make a normal string from your array
for elem in temp_list:
flat += elem
# First separate string by %
# Next filter out empty list elements
# Replace every \n with nothing and remove whitespace from left side.
your_groupings = list(
map(lambda el: el.replace("\n","").lstrip(),
filter(lambda el: len(el) != 0,
flat.split("%"))))
print(your_groupings)
> ['Work Hard Or Go Home', 'Happy Coding']
【解决方案3】:
ls=[]
msg=""
for i in temp_list:
if i=="%":
ls.append (msg [1:].strip ().replace ("\n",""))
msg=""
else:
msg+=i
print(ls)
这里.. 如果元素是“%”,则检查“%”,然后您需要通过删除空格并将“\n”替换为“”来将 msg 添加到列表中。否则将 i 附加到 msg