Matlab在Python中索引和替换

时间:2019-05-18 18:45:50

标签: python matlab indexing

在matalb中,我们可以将向量设为a = [1,3,4],并使用它来访问和替换另一个向量或矩阵的元素,就像这样。

<!-- The core Firebase JS SDK is always required and must be listed first -->       
 <script src="https://www.gstatic.com/firebasejs/6.0.2/firebase-app.js"></script>       

  <!-- TODO: Add SDKs for Firebase products that you want to use        
      https://firebase.google.com/docs/web/setup#config-web-app -->     

  <script>      
   // Your web app's Firebase configuration     
   var firebaseConfig = {       
     apiKey: "AIzaSyBqpSKrmTzi4IL2AFJKyCwu4ZPpJQ33xSw",     
     authDomain: "mathematical-quiz-b71d8.firebaseapp.com",     
     databaseURL: "https://mathematical-quiz-b71d8.firebaseio.com",     
     projectId: "mathematical-quiz-b71d8",      
     storageBucket: "mathematical-quiz-b71d8.appspot.com",      
     messagingSenderId: "507994726644",     
     appId: "1:507994726644:web:e07e6f4c7c7774b1"       
   };       
   // Initialize Firebase       
   firebase.initializeApp(firebaseConfig);      


     function saveToFirebase(score) {       
     var scoreObject = {        
         score: score       
     };     
       var ref = firebase.database().ref();                                         
       ref.on("value", function(snapshot){      
     output.innerHTML = JSON.stringify(snapshot.val(), null, 2);        
 });        

     firebase.database().ref('mathematical-quiz-b71d8').push().set(scoreObject)     
         .then(function(snapshot) {     
             success(); // some success method      
         }, function(error) {       
             console.log('error' + error);      
             error(); // some error method      
         });        
 }      

 saveToFirebase(score);     
 </script>

所以b为[1,1,3,1]

反正在python中执行此操作吗?

我知道我可以做这样的事情:

a=[1,2,4];
b=[1,2,3,4];
b(a)=1

例如,它不允许我替换这些值。

2 个答案:

答案 0 :(得分:1)

Numpy具有类似的功能。但是,请记住,Numpy索引从0开始。而不是从1:

import numpy as np
a = np.array([1, 2, 4])
b = np.array([1, 2, 3, 4])
b[a - 1] = 1
print(b)
#[1 1 3 1]

答案 1 :(得分:-1)

您还可以在python中使用逻辑索引:

import numpy as np

a = np.array([1,1,1,0])
b = np.array([5,6,7,8])

b[a==True]=1
#[1 1 1 8]