问题是使用reduce()来操作数组数组并返回没有子数组的同构数组.例如 - [1,2,[3,[4,5]]]将返回[1,2,3,4,5].
这是有效的代码,考虑到子数组本身不是另一个数组数组 -
var a = [3,[4,[5,[6,7]]]];
var b = 8;
var c = [9,10];
var x = []
var arr = [1,2,a,b,c];
arr = [1,2,3,4,c];
console.log(arr.reduce(function oneArray(a,b)
{
return a.concat(b);
},x))
Run Code Online (Sandbox Code Playgroud)
请注意,我更改了我的arr数组,因为代码不适用于第一个arr数组,即[1,2,a,b,c].对于arr [1,2,3,4,c],返回的对象是[1,2,3,4,9,10]
这是我尝试让它适用于第一个arr-
function oneArray(a,b)
{
if (typeof b == "object")
b = b.reduce(oneArray(x,y),[]);
return a.concat(b);
}
console.log(arr.reduce(oneArray(a,b),x));
Run Code Online (Sandbox Code Playgroud)
这给了我错误
未捕获的TypeError:[object Array]不是函数(匿名函数)@ Flattening.html:27
它将我的函数oneArray解释为数组而不是函数
我理解问题来自于reduce(我认为)只能使用定义为参数的函数.有没有人有一个解决方案,所以我得到[1,2,3,4,5,6,78,9,10]因为我的结果解决了reduce()的限制,除非我错过了什么?
我在nltk文档中找到了这段代码(http://www.nltk.org/_modules/nltk/sentiment/vader.html)
if (i < len(words_and_emoticons) - 1 and item.lower() == "kind" and \
words_and_emoticons[i+1].lower() == "of") or \
item.lower() in BOOSTER_DICT:
sentiments.append(valence)
continue
Run Code Online (Sandbox Code Playgroud)
有人可以解释这个if条件意味着什么吗?
我想在一个 json 文件中存储几个变量。
我知道我可以像这样转储多个变量-
import json
with open('data.json', 'w') as fp:
json.dump(p_id,fp, sort_keys = True, indent = 4)
json.dump(word_list, fp, sort_keys = True, indent = 4)
.
.
.
Run Code Online (Sandbox Code Playgroud)
但是这些变量的存储没有它们的名字,试图加载它们会出错。如何适当地存储和提取我想要的变量?
我想使用我为其生成列表理解的列表的长度以及传递给 any() 函数本身的列表理解中的长度作为条件
我可以用两行来做到这一点 -
li = [1,2,3,4]
lcond = [x for x in li if x > 3]
any(lcond) and len(lcond) >2
Run Code Online (Sandbox Code Playgroud)
但我想一次完成
首先,请注意,我已经经历了其他列表子集问题,这些问题与此处的问题无关。
我有两个清单
>>> l1 = [[(7, -1, 'VBD', 'null', -1, 'looked', 'looked'), (8, 7, 'JJ', 'xcomp', -1, 'shocked', 'shocked')]]
>>>
>>> l2 = [(7, -1, 'VBD', 'null', -1, 'looked', 'looked'), (8, 7, 'JJ', 'xcomp', -1, 'shocked', 'shocked'), (9, 8, 'CC', 'cc', -1, 'and', 'and'), (10, 7, 'JJ', 'xcomp', -1, 'angry', 'angry')]
Run Code Online (Sandbox Code Playgroud)
我正在尝试检查一个是否是另一个的子集。
但在此之前,我检查了从另一个列表中减去一个列表的结果,结果令人失望-
>>> [word for word in l1 if word not in l2]
[[(7, -1, 'VBD', 'null', -1, 'looked', 'looked'), (8, 7, 'JJ', 'xcomp', -1, 'shocked', 'shocked')]]
>>> [word …
Run Code Online (Sandbox Code Playgroud)