java 和 python 相当于 php 的 foreach($array as $key => $value)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1219548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java and python equivalent of php's foreach($array as $key => $value)
提问by Lasoldo Solsifa
In php, one can handle a list of state names and their abbreviations with an associative array like this:
在 php 中,可以使用如下关联数组处理状态名称及其缩写列表:
<?php
$stateArray = array(
"ALABAMA"=>"AL",
"ALASKA"=>"AK",
// etc...
"WYOMING"=>"WY"
);
foreach ($stateArray as $stateName => $stateAbbreviation){
print "The abbreviation for $stateName is $stateAbbreviation.\n\n";
}
?>
Output (with key order preserved):
输出(保留密钥顺序):
The abbreviation for ALABAMA is AL.
The abbreviation for ALASKA is AK.
The abbreviation for WYOMING is WY.
EDIT: Note that the order of array elements is preserved in the output of the php version. The Java implementation, using a HashMap, does not guarantee the order of elements. Nor does the dictionary in Python.
编辑:请注意,数组元素的顺序保留在 php 版本的输出中。使用 HashMap 的 Java 实现不保证元素的顺序。Python 中的字典也没有。
How is this done in java and python? I only find approaches that supply the value, given the key, like python's:
这是如何在java和python中完成的?我只找到提供值的方法,给定密钥,比如 python:
stateDict = {
"ALASKA": "AK",
"WYOMING": "WY",
}
for key in stateDict:
value = stateDict[key]
EDIT: based on the answers, this was my solution in python,
编辑:根据答案,这是我在 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
Which is exactly what was required.
这正是所需要的。
采纳答案by newacct
in Python:
在 Python 中:
for key, value in stateDict.items(): # .iteritems() in Python 2.x
print "The abbreviation for %s is %s." % (key, value)
in Java:
在 Java 中:
Map<String,String> stateDict;
for (Map.Entry<String,String> e : stateDict.entrySet())
System.out.println("The abbreviation for " + e.getKey() + " is " + e.getValue() + ".");
回答by o948
in java for associative array use Map
在 java 中关联数组使用 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()
);
}
}
}
回答by MAK
Another way of doing it in Java. Although a better way has already been posted, this one's syntactically closer to your php code.
在 Java 中执行此操作的另一种方法。虽然已经发布了更好的方法,但这个方法在语法上更接近您的 php 代码。
for (String x:stateDict.keySet()){
System.out.printf("The abbreviation for %s is %s\n",x,stateDict.get(x));
}
回答by MAK
Also, to maintain insertion order, you can use a LinkedHashMap instead of a HashMap.
此外,为了保持插入顺序,您可以使用 LinkedHashMap 而不是 HashMap。
回答by Alexander Ljungberg
In python an ordered dictionaryis available in Python 2.7 (not yet released) and Python 3.1. It's called OrderedDict.
在 Python 中,有序字典在 Python 2.7(尚未发布)和 Python 3.1 中可用。它被称为 OrderedDict。
回答by Milhous
This is the modified code from o948 where you use a TreeMap instead of a HashMap. The Tree map will preserve the ordering of the keys by the key.
这是 o948 中修改后的代码,其中使用 TreeMap 而不是 HashMap。树映射将按键保留键的顺序。
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()
);
}
}
}
回答by A B
Along the lines of Alexander's answer...
沿着亚历山大的回答...
The native python dictionary doesn't maintain ordering for maximum efficiency of its primary use: an unordered mapping of keys to values.
本机 python 字典不维护其主要用途的最大效率的排序:键到值的无序映射。
I can think of two workarounds:
我可以想到两种解决方法:
look at the source code of OrderedDict and include it in your own program.
make a list that holds the keys in order:
states = ['Alabamba', 'Alaska', ...] statesd = {'Alabamba':'AL', 'Alaska':'AK', ...} for k in states: print "The abbreviation for %s is %s." % (k, statesd[k])
查看 OrderedDict 的源代码并将其包含在您自己的程序中。
制作一个按顺序保存密钥的列表:
states = ['Alabamba', 'Alaska', ...] statesd = {'Alabamba':'AL', 'Alaska':'AK', ...} for k in states: print "The abbreviation for %s is %s." % (k, statesd[k])
回答by Denis Tulskiy
TreeMap is not an answer to your question because it sorts elements by key, while LinkedHashMap preserves original order. However, TreeMap is more suitable for the dictionary because of sorting.
TreeMap 不是您问题的答案,因为它按键对元素进行排序,而 LinkedHashMap 保留原始顺序。但是,TreeMap 更适合字典,因为它是排序的。