嗨,
我在试着让这件事奏效。到目前为止,它运行得很好。只有当我尝试遍历列表时,我才得到一个错误。
有什么建议吗?
- orig_file = open ("*Strata1CombinedAll.txt", "r")
- lines = orig_file.readlines()
-
-
-
-
- import fnmatch
- def find(seq, pattern):
- pattern = pattern.lower()
- for i, n in enumerate(seq):
- if fnmatch.fnmatch(n.lower(), pattern):
- return i
- return -1
-
- def index(seq, pattern):
- result = find(seq, pattern)
- if result == -1:
- raise ValueError
- return result
- def contains(seq, pattern):
- return find(seq, pattern) != -1
-
-
- for "*SWD*" in lines:
- begin_line = index(lines, "*SWD*")
- end_line = begin_line + 4
-
- del lines[begin_line:end_line]
-
-
- new_text_file = open ("*test727", "w")
- new_text_file.writelines(lines)
- new_text_file.close()
# 回答1
不能为字符串文本赋值。您必须为标识符赋值。示例:
- >>> lines = [1,2,3,4,5]
- >>> for "astring" in lines:
- ... print "...."
- Traceback (SyntaxError: can't assign to literal
- >>> for n in lines:
- ... print n
- ...
- 1
- 2
- 3
- 4
- 5
- >>>
# 回答2
好的谢谢bvdet。我的问题是,我只知道我的列表元素的一部分,我正在为其循环。
所以我试着用下面的代码来解决这个问题:
- orig_file = open ("*Strata1CombinedAll.txt", "r")
- lines = orig_file.readlines()
-
-
-
-
- import fnmatch
- def find(seq, pattern):
- pattern = pattern.lower()
- for i, n in enumerate(seq):
- if fnmatch.fnmatch(n.lower(), pattern):
- return i
- return -1
-
- def index(seq, pattern):
- result = find(seq, pattern)
- if result == -1:
- raise ValueError
- return result
- def contains(seq, pattern):
- return find(seq, pattern) != -1
-
-
- while contains(lines, "*SWD*"):
- begin_line = index(lines, "*SWD*")
- end_line = begin_line + 4
-
- del lines[begin_line:end_line]
-
-
- new_text_file = open ("*test727", "w")
- new_text_file.writelines(lines)
- new_text_file.close()
-
但我收到了一条错误消息,即"Begin_line"没有索引。如果我不使用While循环,就会得到"Begin_line"的索引。
错误消息:
- Traceback (most recent call last):
- File "*working", line 26, in <module>
- end_line = begin_line + 4
- TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
# 回答3
看见
遍历列表
在一本在线书籍中。我建议您按照示例中的操作遍历列表
- for cheese in cheeses:
- print cheese
并打印列表中的每一项。然后检查每一项以查找所需的字符串,可能使用
In运算符
并进行相应的处理。请注意,您不应从正在遍历的列表中删除。而是将要保留的记录追加到新列表中。
# 回答4
我不能遍历列表,因为我只知道部分值。为了遍历,您需要具有准确的列表元素值,对吗?
所以我需要一种不同的方式。有什么建议吗?
# 回答5
你要么有一个列表,要么没有。你不能有列表的一部分。
# 回答6
嗯,我确实有完整的名单。
我想遍历列表。
我编了一个例子。我想用里面所有的绿色水果做点什么:
- fruit_list = ['greenapples', 'blueapples', 'greenpears', 'bluepears', 'greenoranges', 'blueoranges']
-
- for green* in fruit_list:
但它不起作用,因为我需要像绿苹果一样循环获取完整的值。
我正在寻找解决这个问题的方法
# 回答7
"我想遍历列表"等同于遍历我在第一篇文章中介绍的列表,以及关于如何使用in操作符搜索记录的链接。如果你不打算阅读这些帖子,那么就没有理由进一步发帖。