我只使用这些函数使用递归来反转列表时遇到问题:
def head(xs):
return xs[0]
def tail(xs):
return xs[1:]
def empty(xs):
return len(xs) == 0
Run Code Online (Sandbox Code Playgroud)
我可以做这个:
def p(xs1, xs2):
if not empty(tail(xs1)):
p(tail(xs1), xs2)
xs2.append(head(xs1))
def p05(xs):
s = []
p(xs, s)
return s
Run Code Online (Sandbox Code Playgroud)
有没有办法不使用append()?
我在HashMap中更改值时遇到问题>.首先我这样做:
HashMap<String, ArrayList<Integer>> countries = new HashMap<>();
ArrayList<Integer> medals = new ArrayList<>();
medals.add(0); medals.add(0); medals.add(0);
for(int i = 0; i < COUNTRY.length; i++){
countries.put(COUNTRY[i], medals);
}
Run Code Online (Sandbox Code Playgroud)
我用静态数组中的键填充HashMap,并添加一个填充0,0,0的ArrayList的默认值.然后我这样做:
Integer plus = new Integer(1);
for(int j = 0; j < athletes.size(); j++){
if(j == 3)
break;
Athlete a = athletes.get(j);
ArrayList<Integer> medals = countries.get(a.getCountry());
Integer medal = medals.get(j) + plus;
medals.set(j, medal);
countries.put(a.getCountry(), medals);
}
Run Code Online (Sandbox Code Playgroud)
我有一个填充了运动员的ArrayList,已根据运动员的结果排序.我想要做的就是选择前三名运动员,并更新我的HashMap值,这样ArrayList将有3个数字代表每个国家赢得的金牌,银牌和铜牌数量.问题是,当我尝试用新的ArrayList替换旧值时,它会用新的ArrayList替换HashMap中的所有值,而不是仅使用匹配键的值.
我不知道问题是什么,有什么建议吗?