【javac添加python 列表特性7】解決List各類下標訪問的翻譯

在Python式的列表訪問中,下標訪問有不少種形式,詳見: php

http://ez2learn.com/index.php/python-tutorials/python-tutorials/167-slice java

而這些訪問必定要用到for循環,如把
python

List k=[1,2,3,4,5];
System.out.println(k[1:3:2]); //k[1:3:2]的翻譯要用到for循環
                              //因此只能用函數來替換k[1:3:2]
因此就只能把k[1:3:2]替換成:__list_access(k,1,3,2);

那麼這就意味着我必需要把__list_access的定義添加到每一個類的源代碼中。 函數

爲了解決這個問題,我在javacParser.java裏面,調用了它本身提供的parser,把我本身寫的__list_access的定義parse了進去,而且添加到了語法樹上面。 翻譯

這樣,在translator中進行轉換的時候,就能把k[1:3:2]節點轉換成__list_access(k,1,3,2); code

另外,對於__list_access的定義,今天晚上還真是寫了半天啊。原本覺得挺簡單的。。。沒想到python的list訪問規則這麼麻煩。最後寫出來一份比較簡單的代碼,但願它沒有問題吧: get

private static java.util.List __list_access(java.util.List list, int beg,
			int end, int step) {
		int len = list.size();
		java.util.List tmpList = new java.util.ArrayList();
                
                beg += (beg < 0) ? len : 0;
	        end += (end < 0) ? len : 0;
		if (step == Integer.MAX_VALUE)
			step = 1;
		if (step > 0) {
			if (beg == Integer.MAX_VALUE)
				beg = 0;
			if (end == Integer.MAX_VALUE)
				end = len;
			for (int i = beg; i < end; i += step) {
				tmpList.add(list.get(i));
			}
		} else {
			if (beg == Integer.MAX_VALUE)
				beg = len - 1;
			if (end == Integer.MAX_VALUE)
				end = -1;

			for (int i = beg; i > end; i += step) {
				tmpList.add(list.get(i));
			}
		}

		return tmpList;
}
相關文章
相關標籤/搜索