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

标签 python list nested-lists

我正在开发一个过程 add_to_index,需要 3 个输入:

  • 索引:[[,[url1,url2,...]],...]
  • 关键字:String
  • 一个网址:字符串

如果关键字已经在索引中,则将 url 添加到与该关键字关联的 url 列表中。

如果关键字不在索引中,则将新元素添加到索引中:

[keyword,[url]]

代码

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

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

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

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

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

错误->

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

预期输出:

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

最佳答案

您犯了三个错误,首先您没有使用标志,其次您将 url 作为字符串添加。最后,正如 Kaivosuketaja 在评论中提到的那样,最后应该增加计数。也可以这样做

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

现在的输出是

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

关于python - 将元素附加到嵌套列表中的列表 - python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27492185/

相关文章:

Python。 "zip"字符和列表的最佳方法

python - 从列表中获取特定字符串 - Python

python - 遍历 Python 中的列表列表

python - 如何打印 python 日志记录模块使用的当前日志记录配置?

python - 局部变量和全局变量的区别

java - 如何在 Tomcat 中为 Java EE 应用程序实现套接字

c - hlist_for_each_entry_rcu 是否需要向其中传递额外的指针?

python-3.x - 如何在 pandas 数据框列内的列表中分解/拆分嵌套列表并从中创建单独的列?

python - 将嵌套的数字和字符串列表导出到制表符分隔文件

python - 从 MySQL StoredProcedure 获取多个列表/数据