如何在python中将字符串与列表中的每个元素进行比较

时间:2012-05-27 06:33:21

标签: python python-2.7

大家好我在python中做了一点任务,我需要做以下事情: 我有/ home / user / music,/ home / user / photos等目录由用户插入并且每个新文件夹都是一个级别所以我需要做的是创建一个接收数字的方法然后打印该级别的每个文件夹。

到目前为止,我已经创建了列表,但我不知道如何计算通过键盘添加的字符串中的每个单词“/”并将它们存储起来以便我可以知道级别然后将它们与程序收到的数字。

如果有人能给我至少一些从哪里开始的基本想法,我会非常感激。提前致谢

我想做这样的事情(伪代码)

example of some strings:
/home/user/music
/home/user/photos
/home/user/research
/home/user/music/rock

n=raw_input
if n is equal to a specific amount of "/":
print "every string that has the same amount of "/"

完整的代码所以

print "Please add paths"
l1=raw_input("> ")
l2=raw_input("> ")
while True:
        if l2 == "//":
            break
        else:
            l1=l1+"\n"
            l1=l1+l2
            l2=raw_input("> ")
l1=l1.split("\n")
print "Your paths are"
print "\n"
print "\n" .join(l1)
print "\n"
print l1[1].count("/")

while True:
    print "Choose an option "
    print "1. Amount of sub folders of a path"
    print "2. Amount of folders at a specified level"
    print "3. Max depth between all the folders"
    op=raw_input()
    if op == "1":
        print "Ingrese directorio"
        d=raw_input()
    if op == "2":
        print "Ingrese nivel"
        n=raw_input()
        compararnivel(n)

raw_input()

3 个答案:

答案 0 :(得分:2)

如果您确定用户输入了整个路径名,并且没有相对路径等,您可以按如下方式使用str.count

>>> str.count('/home/usr/music', '/')
3

但是,如果您确实需要操纵路径以首先将它们转换为完整路径格式,和/或进行路径验证,请查看os.path中提供的函数

好的,这里有一些代码解释了我的评论:

  1. 您可以将raw_input数据添加到列表中,而不是将其连接到字符串并按如下方式将其拆分:

    l1 = [] # This makes an empty list
    l2 = raw_input("> ") # Do this statement in a loop if you like
    l1.append(l2) # This appends l2 to the list
    
  2. while循环可以更好地表达如下:

    while l2!='//':
      append l2 to the list
      prompt the user for more input
    
  3. 您应该在第2个while循环中添加结束条件,可能是通过添加第4个提示,要求用户退出

  4. 将所有这些放在一起,你得到以下内容(注意我的评论,他们应该帮助你)

    print "Please add paths, enter // to stop" # It is a good idea to tell the user how to stop the input process
    
    l1 = [] # Create empty list
    l2 = raw_input('> ') # Ideally, you should verify that the user entered a valid path (eg: are '/' allowed at the end of a path?)
    
    while l2 != '//':
        l1.append(l2)
        l2 = raw_input('> ')
    
    print "Your paths are: "
    for path in l1:
        print path
    
    # I am not sure what you are trying to achieve with "print l1[1].count("/")" so leaving it out
    
    # I would suggest to print the options outside the loop, it's a matter of taste, 
    # but do you really want to keep printing them out?
    print "Choose an option: \n\
           1. Number of subfolders of path\n\
           2. Number of folders at a specific path\n\
           3. Max depth between all folders\n\
           4. Quit\n"
    
    choice = raw_input('Enter choice: ')
    
    while choice!='4':
        if choice == '1':
            path = raw_input('Which path are you looking for?')
                # Calculate and print the output here
    
        # This is the question you asked, so I am answering how to process this step    
        if choice == '2':
            level = raw_input('Which level? ') # Ideally, you should verify that the user indeed enters an int here
    
            # Since your python does not seem to be very advanced, let's use a simple for loop:
            num=0
            for path in l1:
                if str.count(path, '/')==int(level):
                    num = num+1
    
            print 'Number of such paths is: ', num
    
        if choice == '3':
            print 'this is not yet implemented'
            # Do something
    
        choice = raw_input('Enter choice: ')
    

答案 1 :(得分:1)

使用str.count(substring),它计算序列出现在字符串中的次数。

paths = [
    '/home/user/music',
    '/home/user/photos',
    '/home/user/research',
    '/home/user/music/rock'
]

level = 3

wantedPaths = [path for path in paths if path.count('/') == level]
print wantedPaths 

答案 2 :(得分:0)

这可以帮到你:

strings = [
    '/home/user/music',
    '/home/user/photos',
    '/home/user/research',
    '/home/user/music/rock',
]

def slash_counter(n):
    return lambda x: x.count('/') == n

n = int(raw_input('Gimme n: '))

for path in filter(slash_counter(n), strings):
    print path