为什么raw_input首先获得价值?

时间:2017-10-03 09:08:48

标签: python python-2.7 list-comprehension

var chessboard = []; 
chessboard.push(["a1", "b1", "c1","d1","e1","f1","g1","h1"]);
chessboard.push(["a2", "b2", "c2","d2","e2", "f2","g2","h2"]);
chessboard.push(["a3", "b3", "c3","d3","e3", "f3","g3","h3"]);
chessboard.push(["a4", "b4", "c4","d4","e4", "f4","g4","h4"]);
chessboard.push(["a5", "b5", "c5","d5","e5", "f5","g5","h5"]);
chessboard.push(["a6", "b6", "c6","d6","e6", "f6","g6","h6"]);
chessboard.push(["a7", "b7", "c7","d7","e7", "f7","g7","h7"]);
chessboard.push(["a8", "b8", "c8","d8","e8", "f8","g8","h8"]);

function findPosition(str){
  for(var i = 0; i< chessboard.length; i++) {
    var index = chessboard[i].indexOf(str);
    if(index>=0) {
      return "row: " + i + ", col: " + index;
    }
  }
}

console.log(findPosition('a5'));
console.log(findPosition('d5'));

对于上面的代码,输入应如下: stu_dict = [{raw_input():int(raw_input())} for i in xrange(1)] print stu_dict 4并打印为r,这意味着它将[{'r': 4}]作为值,4作为关键点在这里!

但是对于下面的代码,它是反向的,第一个输入将分配给键,第二个输入将分配给值

r

为什么会这样?

2 个答案:

答案 0 :(得分:0)

在Python 2中,对于每个键/数据对,首先评估数据,然后从左到右评估对的序列(如果有的话)。

然而,在Python&gt; = 3.5中并非如此,其中修复了错误并首先评估了密钥。

您可以通过从2元组序列构建dict来强制执行预期的行为:

[dict([(raw_input(), int(raw_input()))]) for i in xrange(1)] 

答案 1 :(得分:0)

  

Python从左到右评估表达式。请注意,在评估分配时,右侧会在左侧之前进行评估。

只是它是Python 2.7中的一个错误。

(在Python3中是同样的错误,但现在已经修复了。)