java 和 python 相当于 php 的 foreach($array as $key => $value)
2022-09-03 08:50:22
在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版本的输出中。使用HashMap的Java实现不保证元素的顺序。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
这正是所要求的。