【python 中的for循环】可以动态修改循环范围吗?

发布于 2022-09-01 12:20:48 字数 885 浏览 15 评论 0

R.T.
可以写成这样的代码吗?

file=open('roemo.txt')
list_1=list()
for line in file:
line.rstrip()
#line.split()这样得到的line是一个整体(list的一个元素),把string转化为list
#list_1.append(line) 循环文件中的行数(4行)后,得到是4个元素
line.split()#返回的是一个字符串
list_1=list_1+line.split()
print list_1
print type(line.split())

#----------------------------------------------------------------------

以上是从文件里,把所有单词装到list里面,代码可以运行并且得到满意结果。

#下面是把list_1里面重复的元素给去掉

list_2=list() #新建list_2空的

#遍历list_1中的每一个元素
for i in list_1:
for j in list_2:
#和list_2里的所有元素比较,如果不同,则填充到list_2里面。
if i!=j:
#list_2不断增多。
list_2.append(i)
print list_2

问题来了:list_2的元素是空的!

list_2好像从被定义为空的以后,就没有增加过其中元素。

新人小白刚开始学python,请前辈纠正错误。

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

顾铮苏瑾 2022-09-08 12:20:48
#! /usr/bin/python
# -*- coding: utf-8 -*-

def get_words_from_file(filename):
    words = []
    f = open(filename)
    for line in f:
        line = line.rstrip();
        words += line.split();
    f.close()
    return words

def get_unique_words(words):
    unique_words = []
    for word in words:
        for unique_word in unique_words:
            if word == unique_word:
                break
        else:
            unique_words.append(word)
    return unique_words


if __name__ == "__main__":
    words = get_words_from_file('remove_duplicate_word.py')
    for word in words:
        print word

许一世地老天荒 2022-09-08 12:20:48

1.

pythonlist_2=list() #新建list_2空的
for i in list_1:
    for j in list_2:  ## list_2是空的,下面的不会执行,所以下次到这里还是空的,于是还是不执行。
        if i!=j:
            list_2.append(i)
print list_2   ## 于是最后还是空的

2.for i in list_2,这个list_2在循环中是变化的(不断添加新元素)?
答:在循环中改变list_2 是支持的。
3.顺便教你用一种方法:

pythonlist_2=list() #新建list_2空的
for i in list_1:
    if i not in list_2:  # 是不是有点写英语的感觉 -.-
        list_2.append(i)
print list_2
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文