本文列举了Java与Python的一些常见的语法的对比
一、数据结构
数据结构 | Java | Python |
---|
字符串 | String s = "XXX" | s = "XXX" |
静态数组 | T[] dirs = new T[5] | [0]*5 |
动态数组 | ArrayList<T> | [] |
链表 | LinkedList<T> | N/A |
OrderedSet | TreeSet<T> | N/A |
OrderedMap | TreeMap<T1,T2> | N/A |
HashSet | HashSet<T> | set() |
HashMap | HashMap<T1,T2> | dict() |
堆 | PriorityQueue<T> | [] /heapq.* |
队列 | Queue<T> | queue |
双端队列 | Deque<T> | collections.deque() / queue.deque() |
栈 | Stack<T> | [] /collections.deque() |
二、字符串
字符串方法 | Java | Python |
---|
创建字符串 | String s = "XXX" | s = "XXX" |
将指定的子串str1替换为目标子串str2 | s.replace(str1,str2) | s.replace(str1,str2) |
切片 | s.substring(3) /s.substring(3,5) | s[3:] /s[3:5] /s[::-1] /s[::2] |
查找指定子串在字符串中出现的位置,若未找到则返回-1 | s.indexOf(str,x) | s.find(str,x) |
查找指定子串在字符串中出现的位置,若未找到则引发ValueError异常 | N/A | s.index(str) |
大小写方法 | s.toUpperCase() /s.toLowerCase() | s.title() /s.lower() /s.upper() |
去除空白方法 | s.trim() | s.strip() /s.lstrip() /s.rstrip() |
判断是否以指定子串开头 | s.startsWith(str) | s.startswith(str) |
判断是否以指定子串结尾 | s.endsWith(str) | s.endswith(str) |
获取指定索引的字符 | s.charAt(x) | s[x] |
三、数组
数组方法 | Java | Python |
---|
创建静态数组 | int []a = new int[]{1,2,3} | a = [1,2,3] |
创建一维动态数组 | int []a = new int[n] /Array.fill(a,x) | a = [x]*n |
创建二维动态数组 | int [][]a = new int[m][n] /for (int []row:a){Array.fill(row,x)} | a = [[x]*n for _ in range(m)] |
添加元素 | a.Add(x) | a.append(x) /a.extend(x) |
删除元素 | a.remove() | a.remove() /del a[x] |
四、哈希表
哈希表方法 | Java | Python |
---|
创建 | Map<Integer,Integer> m = new HashMap<>() | a = dict() |
插入键值对 | m.put(key,value) | a[key] = value |
获取值 | value = m.get(key) | value = a[key] |
判断键是否在哈希表中 | m.containsKey(key) | key in a |
五、优先队列/堆
优先队列/堆 | Java(小根堆) | Python(小根堆) |
---|
创建 | Queue<Integer> q = new PriorityQueue<>() | q = [] |
通过数组创建 | Queue<Integer> q = new PriorityQueue<>(a) | heapify(a) |
插入值 | q.offer(x) | heapq.heappush(q,x) |
获取堆顶的值 | int x = q.peek() | x = q[0] |
弹出 | int x = q.poll() | x = heapq.heappop(q) |
六、类型转换
类型转换 | Java | Python |
---|
数组转集合 | Set<Integer> b = new HashSet<>(a) | b = set(a) |
数字转字符串 | String s = Integer.toString(x) | s = str(x) |
字符串转数字 | int x = Integer.parseInt(s) | x = int(s) |
数字转ASCII | int x = c - '0' | x = ord(c) - ord('0') |
ASCII转数字 | int x = character.getNumericValue(c) | x = chr(c) |