我目前有一个看起来像这样的数组:
import numpy as np
import dask.dataframe as dd
import dask
import pandas as pd
import sqlalchemy_utils as sqla_utils
import sqlalchemy as sqla
DATABASE_CONFIG = {
'driver': '',
'host': '',
'user': '',
'password': '',
'port': 5432,
}
DBNAME = 'dask'
url = '{driver}://{user}:{password}@{host}:{port}/'.format(
**DATABASE_CONFIG)
db_url = url.rstrip('/') + '/' + DBNAME
# create db if non-existent
if not sqla_utils.database_exists(db_url):
print('Creating database \'{}\''.format(DBNAME))
sqla_utils.create_database(db_url)
conn = sqla.create_engine(db_url)
# create pandas df with random numbers
df = pd.DataFrame(np.random.randint(0,40,size=(100, 10)), columns=list('ABCDEFGHIJ'))
# add index so that it can be used as primary key later on
df['idx'] = df.index
# create dask df
ddf = dd.from_pandas(df, npartitions=4)
# Write to psql
dto_sql = dask.delayed(pd.DataFrame.to_sql)
out = [dto_sql(d, 'test', db_url, if_exists='append', index=False, index_label='idx')
for d in ddf.to_delayed()]
dask.compute(*out)
我想遍历此数组并找到最长类型的长度。我想要这样的东西:
var array = [
{
"title": "Ender's Game",
"genre": "Science Fiction",
"year": 2008
},
{
"title": "Harry Potter and the Goblet of Fire",
"genre": "fantasy",
"year": 2002
},
{
"title": "Pride and Predjudice",
"genre": "romance",
"year": 1980
}
]
我已经尝试了一些方法,包括以下内容:
longestGenre(array);
15
我尝试的另一种方法是:
var getLongest = (array, key) =>
{
let r = Object.values(array).reduce((res, curr) =>
{
if (!Array.isArray(curr))
return res;
let newMax = curr.reduce(
(r, c) => c[[key]] && (c[[key]].length > r.length) ? c[[key]] : r,
""
);
res = newMax.length > res.length ? newMax : res;
return res;
}, "");
longest = r;
return longest;
}
答案 0 :(得分:6)
您不需要所有这些检查和嵌套循环,只需将数组映射到体裁的长度,然后取最大值即可。
const longestGenre = Math.max(...array.map(movie => movie.genre.length));
或动态:
const longest = (key, array) => Math.max(...array.map(it => it[key].length));
console.log(longest("genre", /*in*/ array));
答案 1 :(得分:0)
您还可以更简洁,更紧凑地使用reduce
。
有效代码段:
var arr = [
{
"title": "Ender's Game",
"genre": "Science Fiction",
"year": 2008
},
{
"title": "Harry Potter and the Goblet of Fire",
"genre": "fantasy",
"year": 2002
},
{
"title": "Pride and Predjudice",
"genre": "romance",
"year": 1980
},
{
"title": "Pride and Predjudice",
"genre": "asdasdasd asdasdasdsa asdasda",
"year": 1980
}
]
var longest = arr.reduce(function (a, b) { return a.genre.length > b.genre.length ? a : b; }).genre.length;
console.log(longest);
答案 2 :(得分:0)
您还可以按length
的{{1}}降序排列对象长度的数组。然后返回将始终保持最大长度的数组的第一个索引。
genre