java和python相当于php的foreach($ array as $ key => $ value) [英] java and python equivalent of php's foreach($array as $key => $value)
问题描述
在php中,可以使用关联数组来处理状态名称及其缩写的列表,如下所示:
< ?php
$ stateArray = array(
ALABAMA=>AL,
ALASKA=>AK,
//等等...
WYOMING=>WY
);
foreach($ stateArray as $ stateName => $ stateAbbreviation){
print$ stateName的缩写是$ stateAbbreviation.\\\
\ n;
}
?>
输出(保留密钥订单):
< pre class =lang-none prettyprint-override>
ALABAMA的缩写是AL。
ALASKA的缩写是AK。
WYOMING的缩写是WY。
编辑:注意数组元素的顺序保留在php版本的输出中。使用HashMap的Java实现不保证元素的顺序。 Python中的字典也没有。
这是如何在java和python中完成的?我只找到提供价值的方法,给定密钥,如python的:
stateDict = {
ALASKA :AK,
WYOMING:WY,
}
for state in stateDict:
value = stateDict [key]
编辑:基于答案,这是我在python中的解决方案,
#一个两元组的列表
stateList = [
('ALABAMA','AL') ,
('ALASKA','AK'),
('WISCONSIN','WI'),
('WYOMING','WY'),
] $ b名称为
$ b,stateList为缩写:
打印名称,缩写
输出:
ALABAMA AL
ALASKA AK
WISCONSIN WI
WYOMING WY
这正是所需要的。
:
for key,value in stateDict.items():#。ititeitems()在P. ython 2.x
print%s的缩写是%s。 Java中的%(键,值)
:
地图<字符串,字符串> stateDict;
for(Map.Entry< String,String> e:stateDict.entrySet())
System.out.println(+ e.getKey()+的缩写是+ e.getValue()+。);
In php, one can handle a list of state names and their abbreviations with an associative array like this:
<?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.
How is this done in java and python? I only find approaches that supply the value, given the key, like python's:
stateDict = {
"ALASKA": "AK",
"WYOMING": "WY",
}
for key in stateDict:
value = stateDict[key]
EDIT: based on the answers, this was my solution in 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.
in Python:
for key, value in stateDict.items(): # .iteritems() in Python 2.x
print "The abbreviation for %s is %s." % (key, value)
in 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和python相当于php的foreach($ array as $ key => $ value)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!