相关疑难解决方法(0)

在Python中展平浅层列表

是否有一种简单的方法可以使用列表推导来展平迭代列表,或者失败,你会认为什么是平衡这样的浅层列表,平衡性能和可读性的最佳方法?

我尝试使用嵌套列表理解来压缩这样的列表,如下所示:

[image for image in menuitem for menuitem in list_of_menuitems]
Run Code Online (Sandbox Code Playgroud)

但我在NameError那里遇到麻烦,因为name 'menuitem' is not defined.谷歌搜索并浏览Stack Overflow后,我得到了一个reduce声明所需的结果:

reduce(list.__add__, map(lambda x: list(x), list_of_menuitems))
Run Code Online (Sandbox Code Playgroud)

但是这个方法相当难以理解,因为我需要那个list(x)调用,因为x是一个Django QuerySet对象.

结论:

感谢所有为此问题做出贡献的人.以下是我学到的内容摘要.我也将其作为社区维基,以防其他人想要添加或更正这些观察结果.

我原来的reduce语句是多余的,用这种方式编写得更好:

>>> reduce(list.__add__, (list(mi) for mi in list_of_menuitems))
Run Code Online (Sandbox Code Playgroud)

这是嵌套列表理解的正确语法(Brilliant summary dF!):

>>> [image for mi in list_of_menuitems for image in mi]
Run Code Online (Sandbox Code Playgroud)

但这些方法都不如使用效率高itertools.chain:

>>> from itertools import chain
>>> list(chain(*list_of_menuitems))
Run Code Online (Sandbox Code Playgroud)

正如@cdleary指出的那样,通过使用chain.from_iterable如下所示来避免*操作符魔术可能是更好的风格:

>>> chain = itertools.chain.from_iterable([[1,2],[3],[5,89],[],[6]])
>>> print(list(chain))
>>> [1, 2, …
Run Code Online (Sandbox Code Playgroud)

python list-comprehension

382
推荐指数
10
解决办法
17万
查看次数

为什么我们的c#图形代码不再工作?

情况如下:

我们有一些通用的图形代码,我们用于其中一个项目.在对代码进行一些清理之后,似乎某些东西不再起作用了(图形输出看起来完全错误).

我对提供正确输出的代码的最后一个版本运行了一个diff,看起来我们改变了我们的一个函数,如下所示:

static public Rectangle FitRectangleOld(Rectangle rect, Size targetSize)
{
    if (rect.Width <= 0 || rect.Height <= 0)
    {
        rect.Width = targetSize.Width;
        rect.Height = targetSize.Height;
    }
    else if (targetSize.Width * rect.Height > 
        rect.Width * targetSize.Height)
    {
        rect.Width = rect.Width * targetSize.Height / rect.Height;
        rect.Height = targetSize.Height;
    }
    else
    {
        rect.Height = rect.Height * targetSize.Width / rect.Width;
        rect.Width = targetSize.Width;
    }

    return rect;
}
Run Code Online (Sandbox Code Playgroud)

static public Rectangle FitRectangle(Rectangle rect, Size targetSize)
{
    if (rect.Width <= 0 || rect.Height <= …
Run Code Online (Sandbox Code Playgroud)

c# operators

4
推荐指数
2
解决办法
470
查看次数

标签 统计

c# ×1

list-comprehension ×1

operators ×1

python ×1