java e python equivalente a foreach do php ($ array quanto $ key => $ value)
-
10-07-2019 - |
Pergunta
No PHP, pode-se lidar com uma lista de nomes de estado e suas abreviaturas com uma matriz associativa como esta:
<?php
$stateArray = array(
"ALABAMA"=>"AL",
"ALASKA"=>"AK",
// etc...
"WYOMING"=>"WY"
);
foreach ($stateArray as $stateName => $stateAbbreviation){
print "The abbreviation for $stateName is $stateAbbreviation.\n\n";
}
?>
Saída (com ordem da chave preservados):
The abbreviation for ALABAMA is AL.
The abbreviation for ALASKA is AK.
The abbreviation for WYOMING is WY.
EDIT: Note que a ordem de elementos da matriz é preservado na saída da versão php. A implementação Java, usando um HashMap, não garante a ordem dos elementos. Nem o dicionário em Python.
Como isso é feito em java e python? Eu só encontrar abordagens que fornecem o valor, dada a chave, como python de:
stateDict = {
"ALASKA": "AK",
"WYOMING": "WY",
}
for key in stateDict:
value = stateDict[key]
EDIT: com base nas respostas, esta foi a minha solução em python,
# a list of two-tuples
stateList = [
('ALABAMA', 'AL'),
('ALASKA', 'AK'),
('WISCONSIN', 'WI'),
('WYOMING', 'WY'),
]
for name, abbreviation in stateList:
print name, abbreviation
Output:
ALABAMA AL
ALASKA AK
WISCONSIN WI
WYOMING WY
Que é exatamente o que era necessário.
Solução
em Python:
for key, value in stateDict.items(): # .iteritems() in Python 2.x
print "The abbreviation for %s is %s." % (key, value)
em Java:
Map<String,String> stateDict;
for (Map.Entry<String,String> e : stateDict.entrySet())
System.out.println("The abbreviation for " + e.getKey() + " is " + e.getValue() + ".");
Outras dicas
em java para uso matriz associativa Map
import java.util.*;
class Foo
{
public static void main(String[] args)
{
Map<String, String> stateMap = new HashMap<String, String>();
stateMap.put("ALABAMA", "AL");
stateMap.put("ALASKA", "AK");
// ...
stateMap.put("WYOMING", "WY");
for (Map.Entry<String, String> state : stateMap.entrySet()) {
System.out.printf(
"The abbreviation for %s is %s%n",
state.getKey(),
state.getValue()
);
}
}
}
Além disso, para manter a ordem de inserção, você pode usar um LinkedHashMap em vez de um HashMap.
Em python um ordenou dicionário está disponível em Python 2.7 (não lançado ainda) e Python 3.1. É chamado OrderedDict.
Este é o código modificado de o948 onde você usar um TreeMap em vez de um HashMap. O mapa da árvore irá preservar a ordem das chaves pela chave.
import java.util.*;
class Foo
{
public static void main(String[] args)
{
Map<String, String> stateMap = new TreeMap<String, String>();
stateMap.put("ALABAMA", "AL");
stateMap.put("ALASKA", "AK");
// ...
stateMap.put("WYOMING", "WY");
for (Map.Entry<String, String> state : stateMap.entrySet()) {
System.out.printf(
"The abbreviation for %s is %s%n",
state.getKey(),
state.getValue()
);
}
}
}
Outra forma de fazê-lo em Java. Apesar de uma maneira melhor já foi publicado, este é sintaticamente mais perto de seu código PHP.
for (String x:stateDict.keySet()){
System.out.printf("The abbreviation for %s is %s\n",x,stateDict.get(x));
}
Ao longo das linhas de resposta de Alexander ...
O dicionário de python nativa não mantém ordenação para a máxima eficiência de seu uso primário:. Um mapeamento desordenada de chaves para valores
Eu posso pensar de duas soluções:
-
olhada no código fonte de OrderedDict e incluí-lo em seu próprio programa.
-
fazer uma lista que possui as chaves em ordem:
states = ['Alabamba', 'Alaska', ...] statesd = {'Alabamba':'AL', 'Alaska':'AK', ...} for k in states: print "The abbreviation for %s is %s." % (k, statesd[k])
TreeMap não é uma resposta à sua pergunta, porque ele ordena os elementos de chave, enquanto LinkedHashMap preserva ordem original. No entanto, TreeMap é mais adequado para o dicionário por causa da classificação.