简体   繁体   English

将元素追加到嵌套列表中的列表 - python

[英]Append element to a list inside nested list - python

I am developing a procedure add_to_index, that takes 3 inputs: 我正在开发一个过程add_to_index,它需要3个输入:

  • an index: [[,[url1,url2,...]],...] 索引:[[,[url1,url2,...]],...]
  • a keyword: String 关键字:字符串
  • a url: String 网址:字符串

If the keyword is already in the index, url is added to the list of urls associated with that keyword. 如果关键字已在索引中,则将url添加到与该关键字关联的URL列表中。

If the keyword is not in the index, a new element is to the index: 如果关键字不在索引中,则新元素将出现在索引中:

[keyword,[url]]

CODE

index = []

def add_to_index(index,keyword,url):
    flag = 0
    count = 0
    for lists in index:
        count += 1
        if(lists[0]==keyword): 
            index[count][1].append(url)

    if(flag ==0):
        index.append([keyword,url])   

#calling the function below

add_to_index(index,'google','http://google.com')
print index

output -> [['google', 'http://google.com']] 输出 - > [['google', 'http://google.com']]

add_to_index(index,'computing','http://acm.org')
print index

output -> [['google', 'http://google.com'], ['computing', 'http://acm.org']] 输出 - > [['google', 'http://google.com'], ['computing', 'http://acm.org']]

add_to_index(index,'google','http://gmail.com') 
print index

error-> 错误 - >

index[count][1].append(url)
AttributeError: 'str' object has no attribute 'append'

Expected output: 预期产量:

 [['google', ['http://google.com', 'http://gmail.com']], 
 ['computing', ['http://acm.org']]]

You have done three mistakes, Firstly you have not used the flag and secondly you are adding the url as a string. 你犯了三个错误,首先你没有使用过这个flag ,其次你把这个url添加为一个字符串。 And finally as Kaivosuketaja has mentioned in the comment, count should be incremented in the end. 最后,正如Kaivosuketaja在评论中提到的那样,计数应该最终增加。 It can be done otherwise as 它可以以其他方式完成

index = []

def add_to_index(index,keyword,url):
    flag = 0
    count = 0

    for lists in index:

        if(lists[0]==keyword): 
            flag = 1
            index[count][1].append(url)
        count += 1

    if(flag ==0):
        index.append([keyword,[url]])   
        # Take note of append away here
#calling the function below

add_to_index(index,'google','http://google.com')
print index

add_to_index(index,'computing','http://acm.org')
print index

add_to_index(index,'google','http://gmail.com') 
print index

The output now is 现在的输出是

[['google', ['http://google.com']]]
[['google', ['http://google.com']], ['computing', ['http://acm.org']]]
[['google', ['http://google.com', 'http://gmail.com']], ['computing', ['http://acm.org']]]

First, you're trying to append to a string that is inside of the list you want to append to. 首先,您尝试附加到要附加到列表内的字符串。 Then, you forgot to say flag = 1 when you've found the keyword. 然后,当您找到关键字时,忘记说flag = 1。 Try the following: 请尝试以下方法:

index = []

def add_to_index(index,keyword,url):
    flag = 0
    count = 0
    for lists in index:
        if(lists[0]==keyword): 
            index[count][1].append(url)
            flag = 1
    count += 1
    if(flag ==0):
        index.append([keyword,url])   

#calling the function below

add_to_index(index,'google','http://google.com')
add_to_index(index,'computing','http://acm.org')
add_to_index(index,'google','http://gmail.com') 
print index

I think you'd be much better off using a defaultdict, though. 不过,我认为使用defaultdict会好得多。 It automatically searches for a keyword and adds the item to the existing keyword, or if it isn't found, creates a new keyword. 它会自动搜索关键字并将项目添加到现有关键字,或者如果找不到,则创建新关键字。

I think this is what you want: 我想这就是你想要的:

index = []

def add_to_index(index,keyword,url):
    flag = 0
    count = 0
    for lists in index:        
        if lists[0] == keyword: 
            lists[1].append(url)
            flag = 1
        count += 1

    if flag == 0:
        index.append([keyword, [url]])   

#calling the function below

add_to_index(index,'google','http://google.com')
print index

I will suggest the use of dictionaries for this: 我会建议使用字典:

index = {}

def add_to_index(index, keyword, url):
    if keyword not in index:
        index[keyword] = [url]
    else:
        index[keyword].append(url)


>>> add_to_index(index,'computing','http://acm.org')
>>> add_to_index(index,'google','http://gmail.com') 
>>> add_to_index(index,'google','http://gmail.com') 
>>> index
{'computing': ['http://acm.org'], 'google': ['http://gmail.com', 'http://gmail.com']}

You could even make index a non global variable by implementing a simple class(ofcourse, this is possible with nested lists too): 您甚至可以通过实现一个简单的类使index成为非全局变量(当然,这也可以使用嵌套列表):

class Index(object):

    def __init__(self):
        self.index = {}

    def add_to_index(self, keyword, url):
        if keyword not in index:
            self.index[keyword] = [url]
        else:
            self.index[keyword].append(url)

You could simplify things a little by getting rid of the flag and count variables. 你可以通过摆脱标志和计数变量来简化一些事情。

index = []

def add_to_index(index, keyword, url):
    for e in index:
        if e[0] == keyword:
            e[1].append(url)
            return

        else:
            index.append([keyword,[url]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM