Java和Python中PHP的foreach($array as $key => $value)等价写法
在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中使用HashMap时,元素的顺序是不固定的。Python中的字典也是如此。
那么在Java和Python中是怎么做到的呢?我只找到了一些方法是根据键来获取值,比如Python的:
stateDict = {
"ALASKA": "AK",
"WYOMING": "WY",
}
for key in stateDict:
value = stateDict[key]
补充说明:根据大家的回答,这是我在Python中的解决方案,
# 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
这正是所需要的结果。
8 个回答
2
在Python中,有一种叫做有序字典的东西,它在Python 2.7(还没发布)和Python 3.1中可以使用。这个有序字典的名字叫OrderedDict。
6
在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()
);
}
}
}
34
在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() + ".");