相关疑难解决方法(0)

Python AttributeError:“ dict”对象没有属性“ append”

我正在创建一个循环,以便将来自用户输入的值连续追加到字典中,但出现此错误:

AttributeError: 'dict' object has no attribute 'append'
Run Code Online (Sandbox Code Playgroud)

到目前为止,这是我的代码:

    for index, elem in enumerate(main_feeds):
        print(index,":",elem)
        temp_list = index,":",elem
    li = {}
    print_user_areas(li)

    while True:
        n = (input('\nGive number: '))


        if n == "":
          break
        else:
             if n.isdigit():
               n=int(n)
               print('\n')
               print (main_feeds[n])

               temp = main_feeds[n]
               for item in user:


                  user['areas'].append[temp]
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

python dictionary for-loop tuples

2
推荐指数
1
解决办法
2万
查看次数

如果在python中不是None,则转换值

如果你需要解析一些有或没有某些条目的XML,你通常会得到这样的模式:

planet = system.findall('.//planet')
row['discoveryyear'] = int(planet.findtext("./discoveryyear")) if planet.findtext("./discoveryyear") else None
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法呢?我想避免第二个planet.findtext调用,但也不想写另一行文本来存储变量

python

1
推荐指数
2
解决办法
1112
查看次数

Python:查找相同的文件并将它们分组

这是课堂作业的一个组成部分,因此如果我无法按照需要深入探讨,我深表歉意。

总而言之,我需要编写一个 python 函数,对所有相同的文件进行分组(即内容相同但文件名不同的文件)。对它们进行分组的目的是最终创建一个 {string: list} 类型的字典,其中列表是相同文件的组,而键(字符串)只是按字母顺序排序时组中的第一个条目。我们得到了一个文件目录。

到目前为止,我有一个使用 glob 迭代每个文件的程序,并且我还使用 filecmp.cmp(file1,file2) 来查找相同的文件。我正在努力解决的是成功比较最多 1000 个文件所需的逻辑。我确信有一种更 Pythonic 的方法来完成此任务,而不是比较 file1 与 file2、file1 与 file3 等。

总之,我知道如何迭代文件列表,并且一旦拥有相同文件组,我知道如何创建字典......我只是对如何有效获取文件组有点迷失。

示例实现 有 7 个文件:A、AA、AAA、B、BB、C、D。文件 A、AA 和 AAA 相同,B 和 BB 相同,而 C 和 D 唯一。我最终的字典应该是:

{'A':[A,AA,AAA],'B':[B,BB],'C':[C],'D':[D]}

在此先感谢您的时间!

python file-io dictionary python-3.x

1
推荐指数
1
解决办法
736
查看次数

将dicts列表映射到dicts列表的dict中

我甚至不确定该怎么称呼它,所以很难搜索.我有,例如,

people = [
    {"age": 22, "first": "John", "last": "Smith"},
    {"age": 22, "first": "Jane", "last": "Doe"},
    {"age": 41, "first": "Brian", "last": "Johnson"},
]
Run Code Online (Sandbox Code Playgroud)

我想要类似的东西

people_by_age = {
    22: [
        {"first": "John", "last": "Smith"},
        {"first": "Jane", "last": "Doe"},

    ],
    41: [
        {"first": "Brian", "last": "Johnson"}
    ]
}
Run Code Online (Sandbox Code Playgroud)

在Python 2中最干净的方法是什么?

python dictionary list python-2.7

-5
推荐指数
1
解决办法
68
查看次数

标签 统计

python ×4

dictionary ×3

file-io ×1

for-loop ×1

list ×1

python-2.7 ×1

python-3.x ×1

tuples ×1