octopusList = {"first": ["red", "white"],
"second": ["green", "blue", "red"],
"third": ["green", "blue", "red"]}
squidList = ["first", "second", "third"]
for i in range(1):
squid = random.choice(squidList)
octopus = random.choice(octopusList[squid])
print squid + " " + octopus
有人可以帮我用JavaScript写这个吗?我的大部分程序都写入了JavaScript,但具体来说,如何获得一个用JavaScript编写的列表列表让我感到困惑。我是一般的编程新手,所以感谢你提出我的问题。 :d
答案 0 :(得分:4)
首先,我想说for i in range(1):
行没用。它只会执行一次内容,而您没有使用i
。
无论如何,你发布的代码应该可以在JavaScript中进行一些调整。首先,您需要重新实现random.choice
。你可以用这个:
function randomChoice(list) {
return list[Math.floor(Math.random()*list.length)];
}
此后,这很简单:
var octopusList = {
"first": ["red", "white"],
"second": ["green", "blue", "red"],
"third": ["green", "blue", "red"]
};
var squidList = ["first", "second", "third"];
var squid = randomChoice(squidList);
var octopus = randomChoice(octopusList[squid]);
// You could use alert instead of console.log if you want.
console.log(squid + " " + octopus);
答案 1 :(得分:1)
js> octopusList = {"first": ["red", "white"],
"second": ["green", "blue", "red"],
"third": ["green", "blue", "red"]}
js> squidList = ["first", "second", "third"]
first,second,third
js> squid = squidList[Math.floor(Math.random() * squidList.length)]
third
js> oct_squid = octopusList[squid]
green,blue,red
js> octopus = oct_squid[Math.floor(Math.random() * oct_squid.length)]
blue
答案 2 :(得分:1)
...具体如何获取包含Javascript编写的列表的列表让我感到困惑。
您也可以(也)使用JavaScript在列表中创建一个列表,如下所示:
var listWithList = [["a,b,c"],["d,"e","f"], ["h","i","j"]]
因为你在JavaScript中编码
o = { "first" : ["red","green"],
"second": ["blue","white"]}
您实际上是在创建一个包含两个属性first
和second
的JavaScript对象,其值是列表(或数组),每个属性都包含元素。这可以正常工作,你可以在icktoofay回答中看到
由于这是一个JavaScript对象,您可以使用此语法来检索它们
listOne = o.first;
listTwo = o.second;
答案 3 :(得分:1)
考虑使用json模块将数据结构从Python转换为JSON格式(这是有效的Javascript) - 反之亦然,如果您需要的话。例如:
>>> octopusList = {"first": ["red", "white"],
... "second": ["green", "blue", "red"],
... "third": ["green", "blue", "red"]}
>>> print json.dumps(octopusList)
{"second": ["green", "blue", "red"], "third": ["green", "blue", "red"], "first": ["red", "white"]}
>>>
如你所见,在这种情况下,“翻译”只是一个身份(字典条目中的排序变化[[在Python中] /对象属性[[在Javascript]]是无关紧要的,因为Python的两个词都没有也没有JS的对象有任何“排序”的概念; - )。