使用元组键从字典创建稀疏矩阵

时间:2017-07-13 10:02:19

标签: python dictionary matrix tuples sparse-matrix

我有以下问题,我希望有人可以帮助我: 我有一个字典作为键d = {(1,2):1,(2,1):1,(1,3):1,(3,1):1,(2,3):1 ,(3,2):1,(1,4):1,(4,1):1,(2,4):1,(4,2):1,(3,4):1,( 4,3):1} 现在,我想创建一个适合元组的矩阵,有四行四列。在我的脑海中,我想它喜欢这个(对不起,如果这看起来有点乱):

public static void main(String[] args) {
CreateBranchCommand createBranchCommand = null;
CheckoutCommand checkoutCommand = null;
Git git = null;
String releaseVersion = "Test";
PushCommand pushCommand = null;
StoredConfig config = null;
try {
/* Consider Git object is created */
git = createGitObject();

/* Checkout Release branch */
checkoutCommand = git.checkout();
checkoutCommand.setName("Release");
checkoutCommand.call();

/* Creating Hotfix Branch */
createBranchCommand = git.branchCreate();
createBranchCommand.setName("hotfix_" + releaseVersion).call();

/* Pushing Hotfix Branch to remote
 * note that the hotfix is not present in remote 
 */
pushCommand = git.push();
pushCommand.setRemote("origin");
pushCommand.setRefSpecs(new RefSpec("hotfix_" + releaseVersion + ":hotfix_" + releaseVersion));
pushCommand.call();

/* Trying to set upstream for newly created hotfix branch */
createBranchCommand.setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM);
createBranchCommand.setStartPoint("origin/" + "hotfix_" + releaseVersion);
createBranchCommand.setForce(true);
createBranchCommand.call();
checkoutCommand.setName("hotfix_" + releaseVersion);
checkoutCommand.call();

/* Editing the configuration file in local */
config = git.getRepository().getConfig();
config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, "hotfix_" + releaseVersion, "remote", "origin");
config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, "hotfix_" + releaseVersion, "merge",
    "refs/heads/hotfix_" + releaseVersion);
config.save();
} catch (Exception exception) {
exception.printStackTrace();
}

}

1:0 1 1 1

2:1 0 1 1

3:1 1 0 1

4:1 1 1 0

其中四个数字a顶部(1 2 3 4)表示与元组中的数字对应的列,并且对于行,左侧(从上到下1 2 3 4)的数字相同。

输出应如下所示:

 1 2 3 4

不幸的是,我完全不知道如何将稀疏矩阵从头脑中变成正确的代码(python 3),看起来我已经达到了智慧的尽头,尽管我确信必须有一个简单的回答这个问题。 如果有人可以帮助我,我会非常感激。 提前致谢

1 个答案:

答案 0 :(得分:0)

单行解决方案,假设您希望在未在字典中指定的位置填充数组0:

 np.asarray([[(d[(x,y)] if (x,y) in d else 0) for y in range(1,5)] for x in range(1,5)])

输出:

array([[0, 1, 1, 1],
       [1, 0, 1, 1],
       [1, 1, 0, 1],
       [1, 1, 1, 0]])

更费力但可能更容易理解的方法是初始化一个空的零数组,然后通过它并在字典中出现的每个位置用0替换0。