如明境 发表于 2022-5-10 10:03:42

获取字典的两个值,并以字符串形式添加到列表里

glds = [{"a":1,"b":2,"c":3}{"a":4,"b":5,"c":6}{"a":7,"b":8,"c":9}]
gid = []
    for gld in glds:
      gid.extend(str(gld['a'],gld['b']))
    print(gid)

运行时提示TypeError: str() argument 2 must be str, not int有没有什么办法解决这个问题

isdkz 发表于 2022-5-10 10:11:02

glds = [{"a":1,"b":2,"c":3},{"a":4,"b":5,"c":6},{"a":7,"b":8,"c":9}]
gid = []
for gld in glds:
    gid.append(f"{gld['a']},{gld['b']}")
print(gid)

如明境 发表于 2022-5-10 10:19:43

isdkz 发表于 2022-5-10 10:11


glds = [{"a":123,"b":234,"c":345},{"a":456,"b":567,"c":678},{"a":789,"b":890,"c":910}]
gid = []
for gld in glds:
    gid.extend(f'{gld["a"]}{gld["b"]}')
print(gid)
不过这个有一个问题,就是会把获取到的值全部拆分,有没有什么办法获取到完整的值呢
这是获取到的值:['1', '2', '3', '2', '3', '4', '4', '5', '6', '5', '6', '7', '7', '8', '9', '8', '9', '0']
我想获取的值是:['123","234","456","567","789","890"]

isdkz 发表于 2022-5-10 10:21:33

如明境 发表于 2022-5-10 10:19
不过这个有一个问题,就是会把获取到的值全部拆分,有没有什么办法获取到完整的值呢
这是获取到的值: ...

你先把我的代码复制过去看看效果先,

你那个会拆分是因为你用了 extend

如明境 发表于 2022-5-10 10:25:36

isdkz 发表于 2022-5-10 10:21
你先把我的代码复制过去看看效果先,

你那个会拆分是因为你用了 extend

好的,我尝试了一下用append,好像可以解决我的问题

isdkz 发表于 2022-5-10 10:36:10

本帖最后由 isdkz 于 2022-5-10 10:37 编辑

如明境 发表于 2022-5-10 10:25
好的,我尝试了一下用append,好像可以解决我的问题

你要想获取到 ["123","234","456","567","789","890"] 的话就这样

glds = [{"a":123,"b":234,"c":345},{"a":456,"b":567,"c":678},{"a":789,"b":890,"c":910}]
gid = []
for gld in glds:
    gid.append(f"{gld['a']}")
    gid.append(f"{gld['b']}")
print(gid)

如明境 发表于 2022-5-10 22:45:27

isdkz 发表于 2022-5-10 10:36
你要想获取到 ["123","234","456","567","789","890"] 的话就这样

谢谢
页: [1]
查看完整版本: 获取字典的两个值,并以字符串形式添加到列表里