Si conoce Java y desea tener una idea rápida de cómo usar Python desde el principio, el siguiente resumen puede proporcionarle una revisión rápida de los tipos de datos. También puede resultarle útil la comparación anterior de Java y Python.
Al comparar los tipos de datos entre Java y Python, puede obtener la diferencia y comenzar a usar Python rápidamente. La comparación también puede ayudar a los desarrolladores a comprender los conceptos comunes compartidos por diferentes lenguajes de programación.
Aparentemente, Java tiene más tipos / estructuras de datos que Python, por lo que enumeraré el concepto más similar de Java para los tipos de datos de Python correspondientes.
1. Cuerdas
Java |
Pitón |
//string
String city = "New York";
String state = "California";//has to be " not '
String lines = "multi-line " +
"string";
|
// string String city = «Nueva York»; String state = «California»; // tiene que ser «no ‘String lines =» multi-line «+» string «;
|
# Strings
city = "New York"
state = 'California'
# multi-line string
lines = """multi-line
string"""
moreLines = '''multi-line
string'''
|
# Strings city = «New York» state = «California» # multi-line string lines = «» «multi-line string» «» moreLines = «» ‘multi-line string’ »
|
En Python, la cadena puede residir en un par de comillas simples y en un par de comillas dobles. Admite la multiplicación: «x» * 3 es «xxx».
2. Números
Java |
Pitón |
//integer numbers
int num = 100;
//floating point numbers
float f = 1.01f;
//float f = 1.01;//wrong!
double d = 1.01;
|
// números enteros int num = 100; // números de coma flotante float f = 1.01f; // float f = 1.01; // ¡incorrecto! doble d = 1,01;
|
# integer numbers
num = 100
num = int("100")
# floating point numbers
f = 1.01
f = float("1.01")
# null
spcial = None
|
# números enteros num = 100 num = int («100») # números de coma flotante f = 1.01 f = float («1.01») # nulo spcial = Ninguno
|
En Java, cuando escribe algo como 1.01, se interpreta como un doble.
Double es un punto flotante IEEE 754 de precisión de 64 bits, mientras que float es un punto flotante IEEE 754 de precisión de 32 bits.
Como un flotante es menos preciso que un doble, la conversión no se puede realizar implícitamente.
3. Nulo
Java |
Pitón |
//null
Object special = null;
|
// nulo Objeto especial = nulo;
|
|
4. Listas
Java |
Pitón |
//arraylist is closest with list in python
ArrayList<Integer> aList =
new ArrayList<Integer>();
//add
aList.add(1);
aList.add(3);
aList.add(2);
aList.add(4);
//index
int n = aList.get(0);
//get sub list
List<Integer> subList =
aList.subList(0, 2);
//1, 3
|
// ArrayList está más cerca de la lista en python ArrayList aList = new ArrayList (); // agregar unaLista.add (1); aList.add (3); aList.add (2); aList.add (4); // índice int n = aList.get (0); // obtener sublista List subList = aList.subList (0, 2); // 1, 3
|
aList = []
aList = [1, 'mike', 'john']
#append
aList.append(2)
# extend
aList.extend(["new","list"])
print aList
#[1, 'mike', 'john', 2, 'new', 'list']
aList = [0,1,2,3,4,5,6]
# size
print 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 mutable
aList[0] = 10
print aList
#[10, 1, 2, 3, 4, 5, 6]
|
aList = []
aList = [1, ‘mike’, ‘john’]
#append aList.append (2) # extender aList.extend ([«new»,»list»]) imprimir una lista #[1, ‘mike’, ‘john’, 2, ‘new’, ‘list’]
aList = [0,1,2,3,4,5,6]
# tamaño print len (aList) # 7 print aList[2]
# 2 imprimir una lista[0:3]
#[0, 1, 2]
imprimir una lista[2:]
#[2, 3, 4, 5, 6]
imprimir una lista[-2]
# 5 #lists son mutables aList[0] = 10 imprimir unaLista #[10, 1, 2, 3, 4, 5, 6]
|
5. Tuplas
Java |
Pitón |
No hay tuplas en Java. |
aTuple = ()
aTuple = (5) # cause error
aTuple = (5,)
print aTuple
print aTuple[0]
#5
|
aTuple = () aTuple = (5) # causa error aTuple = (5,) imprimir aTuple imprimir aTuple[0]
# 5
|
En Python, las tuplas son similares con las listas, y la diferencia entre ellas es que la tupla es inmutable. Eso significa que los métodos que cambian el valor de las listas no se pueden usar en tuplas.
Para asignar una tupla de un solo elemento, tiene que ser: aTuple = (5,). Si se quita la coma, será incorrecto.
6. Conjuntos
Java |
Pitón |
//hashset
HashSet<String> aSet = new HashSet<String>();
aSet.add("aaaa");
aSet.add("bbbb");
aSet.add("cccc");
aSet.add("dddd");
//iterate over set
Iterator<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 aSet
boolean b = aSet.containsAll(bSet);
//union - transform aSet
//into the union of aSet and bSet
aSet.addAll(bSet);
//intersection - transforms aSet
//into the intersection of aSet and bSet
aSet.retainAll(bSet);
//difference - transforms aSet
//into the (asymmetric) set difference
// of aSet and bSet.
aSet.removeAll(bSet);
|
// hashset HashSet aSet = new HashSet (); aSet.add («aaaa»); aSet.add («bbbb»); aSet.add («cccc»); aSet.add («dddd»); // iterar sobre set Iterator iterator = aSet.iterator (); while (iterator.hasNext ()) {System.out.print (iterator.next () + «»); } HashSet bSet = new HashSet (); bSet.add («eeee»); bSet.add («ffff»); bSet.add («gggg»); bSet.add («dddd»); // comprobar si bSet es un subconjunto de aSet boolean b = aSet.containsAll (bSet); // unión – transforma aSet // en la unión de aSet y bSet aSet.addAll (bSet); // intersección – transforma aSet // en la intersección de aSet y bSet aSet.retainAll (bSet); // diferencia: transforma aSet // en la diferencia de conjunto (asimétrica) // de aSet y 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 set
for v in aSet:
print v
bSet = set(['three','four', 'five'])
#union
cSet = aSet | bSet
#set(['four', 'one', 'five', 'three', 'two'])
#intersection
dSet = aSet & bSet
#find elements in aSet not bSet
eSet = aSet.difference(bSet)
#add element
bSet.add("six")
#set(['four', 'six', 'five', 'three'])
|
aSet = set () aSet = set («uno») # un conjunto que contiene tres letras #set ([‘e’, ‘o’, ‘n’]) aSet = set ([‘one’, ‘two’, ‘three’]) #colocar([‘three’, ‘two’, ‘one’]) #un conjunto que contiene tres palabras #iterate over set for v in aSet: print v bSet = set ([‘three’,’four’, ‘five’]) #union cSet = aSet | bSet #set ([‘four’, ‘one’, ‘five’, ‘three’, ‘two’]) #intersection dSet = aSet & bSet #find elements in aSet not bSet eSet = aSet.difference (bSet) #add element bSet.add («six») #set ([‘four’, ‘six’, ‘five’, ‘three’])
|
7. Diccionarios
Los diccionarios en Python son como los mapas en Java.
Java |
Pitón |
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 HashMap
Map<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 value
phoneBook.get("Mike");
//get all key
Set keys = phoneBook.keySet();
//get number of elements
phoneBook.size();
//delete all elements
phoneBook.clear();
//delete an element
phoneBook.remove("Lucy");
|
HashMap phoneBook = new HashMap (); phoneBook.put («Mike», «555-1111»); phoneBook.put («Lucy», «555-2222»); phoneBook.put («Jack», «555-3333»); // iterar sobre HashMap Map map = new HashMap (); para (Map.Entry entrada: map.entrySet ()) {System.out.println («Clave =» + entrada.getKey () + «, Valor =» + entrada.getValue ()); } // obtiene el valor de la clave phoneBook.get («Mike»); // obtener todas las claves Set keys = phoneBook.keySet (); // obtiene el número de elementos phoneBook.size (); // eliminar todos los elementos phoneBook.clear (); // eliminar un elemento phoneBook.remove («Lucy»);
|
#create an empty dictionary
phoneBook = {}
phoneBook = {"Mike":"555-1111",
"Lucy":"555-2222",
"Jack":"555-3333"}
#iterate over dictionary
for key in phoneBook:
print(key, phoneBook[key])
#add an element
phoneBook["Mary"] = "555-6666"
#delete an element
del phoneBook["Mike"]
#get number of elements
count = len(phoneBook)
#can have different types
phoneBook["Susan"] = (1,2,3,4)
#return all keys
print phoneBook.keys()
#delete all the elements
phoneBook.clear()
|
#crear un diccionario vacío phoneBook = {} phoneBook = {«Mike»: «555-1111», «Lucy»: «555-2222», «Jack»: «555-3333»} #iterate over dictionary for key in phoneBook : imprimir (tecla, agenda telefónica[key]) # agregar un elemento phoneBook[«Mary»] = «555-6666» # eliminar un elemento del phoneBook[«Mike»]
#obtener el número de elementos count = len (phoneBook) #puede tener diferentes tipos phoneBook[«Susan»] = (1,2,3,4) #retornar todas las teclas imprimir phoneBook.keys () # borrar todos los elementos phoneBook.clear ()
|
Más sobre las colecciones de Java:
- Diagrama de jerarquía de colecciones
- Conjunto: HashSet frente a TreeSet frente a LinkedHashSet
- Lista: ArrayList vs.LinkList vs.Vector
- Mapa: HashMap frente a TreeMap frente a Hashtable frente a LinkedHashMap