私信  •  关注

Adam.Er8

Adam.Er8 最近创建的主题
Adam.Er8 最近回复了
5 年前
回复了 Adam.Er8 创建的主题 » 将Python字典中的JSON值累积为数组

如果我理解正确,你可以使用 collections.defaultdict ,从源映射到 像这样的目标:

(我添加了一些数据以拥有多个源)

from collections import defaultdict

data = { 
"links": [
{"source":"0","target":"1","weight":1,"color":"white"},
{"source":"0","target":"2","weight":1,"color":"yellow"},
{"source":"0","target":"3","weight":1,"color":"white"},
{"source":"5","target":"7","weight":1,"color":"white"},
{"source":"5","target":"8","weight":1,"color":"yellow"},
{"source":"6","target":"9","weight":1,"color":"white"},
]
}

collectDict = defaultdict(list)
for obj in data["links"]:
    collectDict[obj["source"]].append(obj["target"])

print(dict(collectDict))

输出:

{'0': ['1', '2', '3'], '5': ['7', '8'], '6': ['9']}

这里有另一种方法 itertools.groupby ,

from itertools import groupby

collectDict = {k: [t["target"] for t in g] for k,g in groupby(data["links"], lambda obj: obj["source"])}

print(collectDict)
5 年前
回复了 Adam.Er8 创建的主题 » 如何使用python paramiko包在远程服务器上执行*sudo*命令?

尝试 echo <password> | sudo -S <cmd> 是的。

这是从 sudo manual 以下内容:

-s(stdin)选项使sudo从标准输入而不是终端设备读取密码。密码后面必须跟一个换行符

5 年前
回复了 Adam.Er8 创建的主题 » 在python中,只在双引号后拆分字符串

你可以分开 " 然后去掉不需要的剩余部分,用一个简单的list comp将所有内容用引号重新包装。

string = '"BLAX", "BLAY", "BLAZ, BLUBB", "BLAP"'

parts = ['"{}"'.format(s) for s in string.split('"') if s not in ('', ', ')]

for p in parts:
    print(p)

输出:

"BLAX"
"BLAY"
"BLAZ, BLUBB"
"BLAP"
5 年前
回复了 Adam.Er8 创建的主题 » 使用单行筛选字符串python中的数字

string = "these 5 sentences should not have 2 numbers in them"

newString = " ".join(token for token in string.split() if not token.isdigit())

print(newString)

is

is is an identity comparison operator

is not x is y x is not y

token token.isdigit()