English 中文(简体)
如何审查清单,并改变名单上的现有内容?
原标题:How to look into a list and varify the existing of elements inside the list?
  • 时间:2015-07-04 16:16:53
  •  标签:
  • python

试图写成一部已经完成任务的法典的I m New to Zhu and I m:

  • I need to open the file romeo.txt and read it line by line.
  • For each line, split the line into a list of words using the split() function. * * Build a list of words as follows:
    • For each word on each line check to see if the word is already in the list
    • If not append it to the list.
  • When the program completes, sort and print the resulting words in alphabetical order.

http://www.pythonlearn.com/code/romeo.txt” rel=“nofollow”http://www.pythonlearn.com/code/romeo.txt

这是我迄今为止所做的:

fname = raw_input("Enter file name: ")
if len(fname) == 0:
    fname = open( romeo.txt )
newList = []
for line in fname:
    words = line.rstrip().split()

    print words

我知道,我需要使用另一个<条码>查询,以检查任何缺失的词句,最后,我需要利用<条码>sort(的功能加以分类。 灰色译员给我一个错误说,如果不存在的话,我必须使用<编码>append(<>append(>)。

我设法用我的代码编制以下清单:

[ But ,  soft ,  what ,  light ,  through ,  yonder ,  window ,  breaks ] ←      Mismatch
[ It ,  is ,  the ,  east ,  and ,  Juliet ,  is ,  the ,  sun ]
[ Arise ,  fair ,  sun ,  and ,  kill ,  the ,  envious ,  moon ]
[ Who ,  is ,  already ,  sick ,  and ,  pale ,  with ,  grief ]

但产出应如此:

[ Arise ,  But ,  It ,  Juliet ,  Who ,  already ,  and ,  breaks , east ,  envious ,  fair ,  grief ,  is ,  kill ,  light ,  moon ,  pale ,  sick , soft ,  sun ,  the ,  through ,  what ,  window ,  with ,  yonder ]

我如何调整我的法典以产生这一产出?

Important Note: To everyone wants to help, Please make sure that you go from my code to finish this tast as it s an assignment and we have to follow the level of the course. Thanks

这是我对法典的更新:

fname = raw_input("Enter file name: ")
if len(fname) == 0:
    fname = open( romeo.txt )
newList = list()
for line in fname:
    words = line.rstrip().split()
    for i in words:
        newList.append(i) 
        newList.sort()



print newList

[ Arise , But , It , Juliet , Who , already , and , and , and , breaks , east , envious , fair , grief , is , is , is , kill , light , moon , pale , sick , soft , sun , sun , the , the , the , through , what , window , with , yonder ]
But I m getting duplication! Why is that and how to avoide that?

问题回答
fname = raw_input("Enter file name: ")
fh = open(frame)
lst = list()
for line in fh
    for i in line.split():
        lst.append(i)
lst.sort()
print list(set(lst))

上述法典对我有效。

fname = input("Enter file name: ") #Ask the user for the filename.
fh = open(fname)                   #Open the file.
lst = list()                       #Create a list called lst.
for line in fh:                    #For each line in the fh?
     words = line.split() .        #Separate the words in the line.
     for word in words :           #For each word in words.
         if word not in lst :      #If word not in the lst.
            lst.append(word)       #Add the word.
     elif word in lst :            #Continue looping.
        continue
lst.sort()
print(lst)                         #Print the lst.

我长期以来一直与这一问题作斗争,同时,我正在“在线”讲授课程。 但是,如果没有太多的nes或 lo,就能够做到这一点。 希望这一帮助。

file = input( Enter File Name:  )
try:
    file = open(file)
except:
    print( File Not Found )
    quit()
F = file.read()
F = F.rstrip().split()
L = list()
for a in F:
    if a in L:
        continue
    else:
        L.append(a)
print(sorted(L))

你们想把所有言词汇集在一起。 Or, uh, a set,因为规定具有独一无二的性质,你不关心任何途径。

fname = raw_input("Enter file name: ")
if len(fname) == 0: fname =  romeo.txt )
with open(fname,  r ) as f: # Context manager
    words = set()
    for line in f: words.update(line.rstrip().split())
#Now for the sorting
print sorted(words, key = str.lower)

I m using key = str.down 因为我假定你想用人字母而不是计算机字母进行分类。 如果你想要计算机字母,就能够消除这一论点。

现在,如果你真想使用一份清单,尽管它为这一申请提供了O(n)。

words = []
with open(filename, "r") as f:
   for word in line.rstrip().split():
       if word not in words:
           words.append(word)

粗略方式是使用一套办法,以编制一份独一无二的措辞清单,并逐条逐行相互交汇:

with open(fn) as f:    # open your file and auto close it
    uniq=set()         # a set only has one entry of each
    for line in f:     # file line by line
        for word in line.split():    # line word by word
            uniq.add(word)           # uniqueify by adding to a set

print sorted(uniq)     # print that sorted

你们可以做些什么 Python Python prehensi prehensi 1) 1) 1)

with open(fn) as f:
    uniq={w for line in f for w in line.split()} 

8.4 Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort and print the resulting words in alphabetical order. You can download the sample data at http://www.pythonlearn.com/code/romeo.txt

fname = raw_input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
    line=line.rstrip()
    a=line.split()
    i=0
    for z in a:
        if z not in lst:
        lst.append(z)
    else:
        continue
lst.sort()
print lst
fname = raw_input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
  word=line.rstrip().split()
  for i in word:
        if i in lst:
          continue
        else:
            lst.append(i)
        lst.sort()
print lst

I am doing the EXACT SAME Python Online course in Coursera - "Python for everybody" - and It took me 3 days to complete this assignment and come up with the following piece of code. A short recommendation just if you care 1) Try writing the code exclusively without ANY hint or help - try at least 10 hours 2) Leave the questions as "Last Resort" When you don t give up and write the code independently the reward is IMMENSE.

For the following code I used EXCLUSIVELY the materials covered in week 4 for the course

fname = input("Enter file name: ") 
fh = open("romeo.txt")
newlist = list ()
for line in fh:
    words = line.split()
    for word in words:
        if word not in newlist :
            newlist.append (word)
        elif word in newlist :
            continue
newlist.sort ()
print (newlist)
fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
    line=line.rstrip()
    line=line.split()
    for i in line:
        if i in lst:
           continue
        else:
           lst.append(i)

lst.sort()
print (lst)
fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
    for i in line.split():
        if i not in lst:
            lst.append(i)
lst.sort()
print(lst)
final_list = list()
file_name = input( Enter file:  )
try:
    file_handle = open(file_name)
    for line in file_handle:
        words = line.rstrip().split()
        for word in words:
            if final_list.__contains__(word):
                continue
            else:
                final_list.append(word)
    final_list = sorted(final_list)
    print(final_list)
except:
    print( Can not open file. )




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签