2017-04-24 170 views
0

所以在Python中,我有一個矩陣如下:轉換矩陣的元素爲整數

theMatrix = [["String", "0"],["String2", "1"]] 

,我想所有的數字在每個表的索引1轉換爲整數。

結果:

theMatrix = [["String", 0],["String2", 1]] 

這需要的不僅僅是兩個列表中的工作:

eg. theMatrix = [["String", 0],["String2", 1],["String3", 2],["String4", 3]] 
+0

您使用什麼語言? MATLAB? –

+0

對不起,我正在使用Python。我知道我錯過了一些東西! –

回答

0

請詳細說明編程語言,並在內部列表將會有更多的元素或它們是總是元組?你想將字符串格式的每一個整數轉換爲int或只是內部列表中的第二項?這個數據結構的用意是什麼?你可能需要考慮的是字典或散列表。只是想一想它會適合你的解決方案。

對於Python語言,你可以有內部列表元素多,總是位置1已經改變,然後將下面的代碼可以幫助

for innerList in theMatrix: 
    if len(innerList) > 1: 
     value = int(innerList[1]) 
     innerList[1] = value if value >= 0 else 0 
+0

我正在使用python,內部列表中可能有更多元素,但是我想要轉換爲整數的字符串的索引將始終是相同的,即在索引1處。我將需要執行所有算法所以我不確定字典能幫助我。 –

0
theMatrix = [["String", '0'],["String2", '1'],["String3", '2'],["String4", '3']] 
#iterate the list of lists and convert the int string to int. 
[[e[0],int(e[-1])] for e in theMatrix] 
Out[222]: [['String', 0], ['String2', 1], ['String3', 2], ['String4', 3]]