java vs python(2)

来源:互联网 发布:企业社保报盘软件 编辑:程序博客网 时间:2024/06/11 05:12

If you know Java and want to quickly get a sense of how to use Python from the very beginning, the following summary can provide you a quick review of data types. You may also find the previouscomparison of Java and Python useful.

By comparing data types between Java and Python, you can get the difference and start using Python quickly. Comparision also can also help developers understand the common concepts shared by different programming languages.

Apparently, Java has more data types/structures than Python, so I will list the most similar concept from Java for the corresponding Python data types.

1. Strings

JavaPython
//stringString city = "New York";String state = "California";//has to be " not ' String lines = "multi-line " +"string";
# Stringscity = "New York"state = 'California' # multi-line stringlines = """multi-linestring"""moreLines = '''multi-linestring'''

In python, string can reside in a pair of single quotes as well as a pair of double quotes. It supports multiplication: “x”*3 is “xxx”.

2. Numbers

JavaPython
//integer numbersint num = 100; //floating point numbersfloat f = 1.01f; //float f = 1.01;//wrong! double d = 1.01;
# integer numbersnum = 100num = int("100") # floating point numbersf = 1.01f = float("1.01") # nullspcial = None

In Java, when you type something like 1.01, its interpreted as a double.
Double is a 64-bit precision IEEE 754 floating point, while float is a 32-bit precision IEEE 754 floating point.
As a float is less precise than a double, the conversion cannot be performed implicitly.

3. Null

JavaPython
//nullObject special = null;
# nullspcial = None

4. Lists

JavaPython
//arraylist is closest with list in pythonArrayList<Integer> aList = new ArrayList<Integer>(); //addaList.add(1);aList.add(3);aList.add(2);aList.add(4); //indexint n = aList.get(0); //get sub listList<Integer> subList = aList.subList(0, 2);//1, 3
aList = []aList = [1, 'mike', 'john'] #appendaList.append(2) # extendaList.extend(["new","list"]) print aList#[1, 'mike', 'john', 2, 'new', 'list'] aList = [0,1,2,3,4,5,6]# sizeprint len(aList)#7 print aList[2]#2 print aList[0:3]#[0, 1, 2] print aList[2:]#[2, 3, 4, 5, 6] print aList[-2]#5 #lists are mutableaList[0] = 10print aList#[10, 1, 2, 3, 4, 5, 6]

5. Tuples

JavaPythonNo tuples in Java.
aTuple = ()aTuple = (5) # cause erroraTuple = (5,) print aTupleprint aTuple[0]#5

In Python, tuples are similar with lists, and the difference between them is that tuple is immutable. That means methods that change lists’ value can not be used on tuples.

To assign a single element tuple, it has to be: aTuple = (5,). If comma is removed, it will be wrong.

6. Sets

JavaPython
//hashsetHashSet<String> aSet = new HashSet<String>();aSet.add("aaaa");aSet.add("bbbb");aSet.add("cccc");aSet.add("dddd"); //iterate over setIterator<String> iterator = aSet.iterator();while (iterator.hasNext()) {System.out.print(iterator.next() + " ");} HashSet<String> bSet = new HashSet<String>();bSet.add("eeee");bSet.add("ffff");bSet.add("gggg");bSet.add("dddd"); //check if bSet is a subset of aSetboolean b = aSet.containsAll(bSet); //union - transform aSet //into the union of aSet and bSetaSet.addAll(bSet); //intersection - transforms aSet //into the intersection of aSet and bSetaSet.retainAll(bSet);  //difference - transforms aSet //into the (asymmetric) set difference// of aSet and bSet. aSet.removeAll(bSet);
aSet = set()aSet = set("one") # a set containing three letters#set(['e', 'o', 'n']) aSet = set(['one', 'two', 'three'])#set(['three', 'two', 'one'])#a set containing three words #iterate over setfor v in aSet:    print v bSet = set(['three','four', 'five']) #union cSet = aSet | bSet#set(['four', 'one', 'five', 'three', 'two']) #intersectiondSet = aSet & bSet #find elements in aSet not bSeteSet = aSet.difference(bSet) #add elementbSet.add("six")#set(['four', 'six', 'five', 'three'])

7. Dictionaries

Dictionaries in Python is like Maps in Java.

JavaPython
HashMap<String, String> phoneBook =                         new HashMap<String, String>();phoneBook.put("Mike", "555-1111");phoneBook.put("Lucy", "555-2222");phoneBook.put("Jack", "555-3333"); //iterate over HashMapMap<String, String> map = new HashMap<String, String>();for (Map.Entry<String, String> entry : map.entrySet()) {    System.out.println("Key = " + entry.getKey() +      ", Value = " + entry.getValue());} //get key valuephoneBook.get("Mike"); //get all keySet keys = phoneBook.keySet(); //get number of elementsphoneBook.size(); //delete all elementsphoneBook.clear(); //delete an elementphoneBook.remove("Lucy");
#create an empty dictionaryphoneBook = {}phoneBook = {"Mike":"555-1111",              "Lucy":"555-2222",              "Jack":"555-3333"} #iterate over dictionaryfor key in phoneBook:    print(key, phoneBook[key]) #add an elementphoneBook["Mary"] = "555-6666" #delete an elementdel phoneBook["Mike"] #get number of elementscount = len(phoneBook) #can have different typesphoneBook["Susan"] = (1,2,3,4) #return all keysprint phoneBook.keys() #delete all the elementsphoneBook.clear()

原创粉丝点击