java和python相当于php的foreach($array as$key=>$value)
-
10-07-2019 - |
题
在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";
}
?>
输出(与主要以保留):
The abbreviation for ALABAMA is AL.
The abbreviation for ALASKA is AK.
The abbreviation for WYOMING is WY.
编辑:请注意,该命令的阵列的要素是保留在输出的php版本。Java执行情况,使用哈希,不能保证顺序的要素。也不在字典中的蟒蛇。
这是怎么做java和蟒蛇?我只找到办法,供应价值,鉴于关键的,就像python:
stateDict = {
"ALASKA": "AK",
"WYOMING": "WY",
}
for key in stateDict:
value = stateDict[key]
编辑:基于答案,这是我的解决方案在蟒蛇,
# a list of two-tuples
stateList = [
('ALABAMA', 'AL'),
('ALASKA', 'AK'),
('WISCONSIN', 'WI'),
('WYOMING', 'WY'),
]
for name, abbreviation in stateList:
print name, abbreviation
输出:
ALABAMA AL
ALASKA AK
WISCONSIN WI
WYOMING WY
这是什么是必要的。
解决方案
在Python:
for key, value in stateDict.items(): # .iteritems() in Python 2.x
print "The abbreviation for %s is %s." % (key, value)
在Java中:
Map<String,String> stateDict;
for (Map.Entry<String,String> e : stateDict.entrySet())
System.out.println("The abbreviation for " + e.getKey() + " is " + e.getValue() + ".");
其他提示
在Java进行关联数组使用地图
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()
);
}
}
}
此外,为了维持插入顺序,可以使用LinkedHashMap中,而不是一个HashMap中。
在一个蟒有序字典是在Python 2.7(不可用尚未发布)和Python 3.1。这就是所谓的OrderedDict。
这是从那里使用TreeMap代替一个HashMap的o948修改后的代码。树地图将由密钥保存密钥的顺序。
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()
);
}
}
}
在Java中这样做的另一种方法。虽然有更好的方式已经发布,这其中的语法更接近你的PHP代码。
for (String x:stateDict.keySet()){
System.out.printf("The abbreviation for %s is %s\n",x,stateDict.get(x));
}
沿线的亚历山大的回答...
本机python字典不会保持订购最高的效率为其主要用途:一个无序的映射键的价值观。
我可以想到的两个解决方法:
看看源代码的OrderedDict和包括它在自己的程序。
做一个列表,持有的钥匙,以便:
states = ['Alabamba', 'Alaska', ...] statesd = {'Alabamba':'AL', 'Alaska':'AK', ...} for k in states: print "The abbreviation for %s is %s." % (k, statesd[k])
TreeMap的不是回答你的问题,因为它按关键要素,而LinkedHashMap的保留原来的顺序。然而,TreeMap中是更适合,因为分选的字典。
不隶属于 StackOverflow