Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 避免重复并为for循环中的每个单例赋值_Python_Loops - Fatal编程技术网

Python 避免重复并为for循环中的每个单例赋值

Python 避免重复并为for循环中的每个单例赋值,python,loops,Python,Loops,我试图处理重复和为for循环中的每个单例赋值失败的问题 首先,我创建从一个节点到它连接到的节点的边: ti = "D" #node from lst = ["A", "B", "C"] #nodes to packaged = [(ti, l) for l in lst] # a list of edges (from - to) l_lst = len(lst) ## length of lst, *i.e.* degree of ti weight = 1 / float(l_ls

我试图处理重复和为for循环中的每个单例赋值失败的问题

首先,我创建从一个节点到它连接到的节点的边:

ti = "D" #node from
lst = ["A", "B", "C"] #nodes to

packaged = [(ti, l) for l in lst]  # a list of edges (from - to)

l_lst = len(lst)  ## length of lst, *i.e.* degree of ti

weight = 1 / float(l_lst)  # edge weight, normalized by length of lst

for pair in packaged:
    print (packged, weight)  
这给了我

([('D', 'A'), ('D', 'B'), ('D', 'C')], 0.3333333333333333)
([('D', 'A'), ('D', 'B'), ('D', 'C')], 0.3333333333333333)
([('D', 'A'), ('D', 'B'), ('D', 'C')], 0.3333333333333333)
然而,我想实现的是:

('D', 'A'), 0.3333333333333333
('D', 'B'), 0.3333333333333333
('D', 'C'), 0.3333333333333333
如何避免重复并为每对节点(边)分配权重

谢谢

您需要的是:

ti = "D" #node from
lst = ["A", "B", "C"] #nodes to

packaged = [(ti, l) for l in lst]  # a list of edges (from - to)

l_lst = len(lst)  ## length of lst, *i.e.* degree of ti

weight = 1 / float(l_lst)  # edge weight, normalized by length of lst

for pair in packaged:
    print (pair, weight)  
在for循环中使用
pair
而不是
packated

您需要的是:

ti = "D" #node from
lst = ["A", "B", "C"] #nodes to

packaged = [(ti, l) for l in lst]  # a list of edges (from - to)

l_lst = len(lst)  ## length of lst, *i.e.* degree of ti

weight = 1 / float(l_lst)  # edge weight, normalized by length of lst

for pair in packaged:
    print (pair, weight)  
在for循环中使用
pair
而不是
packated
一个简单的修复:

for pair in packaged:
    print (pair, weight)  
一个简单的解决方案:

for pair in packaged:
    print (pair, weight)  

嗯:
打印(成对,重量)
?您在每次迭代中打印
打包的
-您应该打印
成对的
吗?哈哈。谢谢我完全把自己搞糊涂了。嗯:
打印(成对,重量)
?你每次迭代都打印
打包的
-你应该打印
成对的
吗?哈哈。谢谢我完全弄糊涂了。