[英]Removing a string from a list inside a list of lists
What I'm trying to achieve here in a small local test is to iterate over an array of strings, which are basically arrays of strings inside a parent array. 我要在一个小型本地测试中实现的目标是迭代一个字符串数组,该字符串数组基本上是父数组中的字符串数组。
I'm trying to achieve the following... 我正在努力实现以下目标...
So far I've tried the following, but I'm struggling with an error that I don't know where it does come from... 到目前为止,我已经尝试了以下方法,但是我一直在努力解决一个错误,我不知道错误的根源...
lines = map(lambda l: str.replace(l, "\n", ""),
list(open("PATH", 'r')))
splitLines = map(lambda l: l.split(','), lines)
for line in splitLines:
for keyword in line:
print(list(splitLines).remove(keyword))
But I'm getting the following error... 但是我收到以下错误...
ValueError: list.remove(x): x not in list
Which isn't true as 'x' isn't a string included in any of the given test arrays. 这是不正确的,因为“ x”不是任何给定测试数组中包含的字符串。
SAMPLE INPUT (Comma separated lines in a text file, so I get an array of strings per line): 样本输入(文本文件中用逗号分隔的行,因此我每行得到一个字符串数组):
[['a', 'b', 'c'], ['e', 'f', 'g'], ['b', 'q', 'a']]
SAMPLE OUTPUT: 样品输出:
[['a', 'b', 'c'], ['e', 'f', 'g'], ['q']]
You can keep track of previously seen strings using a set
for fast lookups, and using a simple list comprehension to add elements not found in the previously seen set
. 您可以使用
set
进行快速查找,并使用简单的列表推导添加在以前见过的set
找不到的元素,以跟踪先前见过的字符串。
prev = set()
final = []
for i in x:
final.append([j for j in i if j not in prev])
prev = prev.union(set(i))
print(final)
Output: 输出:
[['a', 'b', 'c'], ['e', 'f', 'g'], ['q']]
inputlist = [['a', 'b', 'c'], ['e', 'f', 'g'], ['b', 'q', 'a']]
scanned=[]
res=[]
for i in inputlist:
temp=[]
for j in i:
if j in scanned:
pass
else:
scanned.append(j)
temp.append(j)
res.append(temp)
[['a', 'b', 'c'], ['e', 'f', 'g'], ['q']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.