首页 \ 问答 \ 在Python中列表操作(List manipulation in python)

在Python中列表操作(List manipulation in python)

你已经列出了一份清单。 列表长度可能会有所不同。

As an example:
1. ll = [1,2,3]
2. ll = [1,2,3,4]
3. ll = [1,2] 
4. ll = []

我想存储三个变量的值,

var1,var2,var3 = None,None,None

If ll[0] exists then var1 = ll[0]
If ll[1] exists then var2 = ll[1]
If ll[3] exists then var3 = ll[2]

我已经写了解决方案,但它包含如果其他。 我写的代码: -

var1,var2,var3 = None,None,None
if len(ll) == 1: 
    var1,var2,var3 = ll[0],None,None
elif len(ll) == 2: 
    var1,var2,var3 = ll[0],ll[1],None
else:
    var1,var2,var3 = ll[0],ll[1],ll[2]

有没有什么好的方法可以解决这个问题,而不使用IF / Else。


You have given a list. Length of list can vary.

As an example:
1. ll = [1,2,3]
2. ll = [1,2,3,4]
3. ll = [1,2] 
4. ll = []

I want to store value in three variables,

var1,var2,var3 = None,None,None

If ll[0] exists then var1 = ll[0]
If ll[1] exists then var2 = ll[1]
If ll[3] exists then var3 = ll[2]

I have written the solution but it contains if else. Code I have written:-

var1,var2,var3 = None,None,None
if len(ll) == 1: 
    var1,var2,var3 = ll[0],None,None
elif len(ll) == 2: 
    var1,var2,var3 = ll[0],ll[1],None
else:
    var1,var2,var3 = ll[0],ll[1],ll[2]

Is there any good method to solve this without using IF/Else.


原文:https://stackoverflow.com/questions/19515609
更新时间:2022-12-01 07:12

最满意答案

我最终在http://www.infoq.com/articles/Rails-Performance (“看看Rails中的常见性能问题”)中阅读了一篇优秀的文章。 然后我按照作者的建议在请求处理期间缓存计算:

def estimated_costs
  @estimated_costs ||=
    begin
      # tedious vector math
    end
end

因为我的工作表一遍又一遍地处理上面的内容,然后基于这些结果来计算更多的行,这使得蝙蝠的加速度提高90% 。 本来应该是平淡无奇的,但它开始只有几个总数,然后我把原型展示给了客户,并且从那里开始滚动:)

我还想知道基于数组的数学可能是低效的,所以我用NArray( http://narray.rubyforge.org/ )替换了数组的Ruby数组。 加速是微不足道的,但代码更清洁,所以它保持这种方式。

最后,我放置了一些对象缓存。 数据库中的“幻数”最多只会每年更改几次,其中一些已加密,但在大部分计算中需要使用它们。 这是缓慢成熟的缓慢果实,并且再削减1.25秒。

接下来我将着眼于加载关联,因为可能需要一些时间来保存,我会做一个简单的比较,发送“只是数据”与发送HTML,就像@tadman建议的那样。 关于我可以缓存的唯一部分是导航边栏。 所有其他内容取决于请求参数。

感谢您的建议!


I ended up reading an excellent article at http://www.infoq.com/articles/Rails-Performance ("A Look At Common Performance Problems In Rails"). Then I followed the author's suggestion to cache computations during request processing:

def estimated_costs
  @estimated_costs ||=
    begin
      # tedious vector math
    end
end

Because my worksheet does stuff like the above over and over, and then builds on those results to calculate some more rows, this resulted in a 90% speedup right off the bat. Should have been plain as day, but it started with just a few totals, then I showed the prototype to the customer, and it snowballed from there :)

I also wondered whether my array-based math might be inefficient, so I replaced the Ruby Arrays of numbers with NArray (http://narray.rubyforge.org/). The speedup was negligible but the code's cleaner, so it's staying that way.

Finally, I put some object caching in place. The "magic numbers" in the database only change a few times a year at most, and some of them are encrypted, but they need to be used in most of the calculations. That's low-hanging fruit ripe for caching, and it shaved off another 1.25 seconds.

I'll look at eager loading of associations next, as there's probably some time to save there, and I'll do a quick comparison of sending "just the data" vs sending the HTML, as @tadman suggested. About the only partial I can cache is the navigation sidebar. All of the other content depends on the request parameters.

Thanks for your suggestions!

相关问答

更多
  • 我想我的经验法则是使用帮手构建一个单一的“单位”的显示器 - 像包含一个链接的跨度 - 并使用部分来构建一个更复杂的显示单元,由多个单元组成“显示 - 像网格或菜单。 I guess my rule of thumb is to use a helper to build a single "unit" of display -- like a span containing a link -- and to use a partial to build a more complex unit of dis ...
  • 通过将其放置在config / initializers / anti_freeze_hack.rb中进行修复: module ActionDispatch module Routing class RouteSet alias inspect to_s end end end 感谢Amala为我链接正确的话题:D Fixed by placing this in config/initializers/anti_freeze_hack.rb : module Acti ...
  • 我最终在http://www.infoq.com/articles/Rails-Performance (“看看Rails中的常见性能问题”)中阅读了一篇优秀的文章。 然后我按照作者的建议在请求处理期间缓存计算: def estimated_costs @estimated_costs ||= begin # tedious vector math end end 因为我的工作表一遍又一遍地处理上面的内容,然后基于这些结果来计算更多的行,这使得蝙蝠的加速度提高了90% 。 ...
  • 其实,你的直觉可能是错误的(我强调可能,请参阅我的评论以下关于测量)。 要将字符串转换为整数需要一系列的乘/加操作。 要将整数转换为字符串需要除法/模数。 很可能前者比后者快。 但我想指出,你应该衡量,而不是猜测! 这个景观充斥着依赖不正确假设的算法尸体。 我还想指出的是,除非您的计算器每秒钟都要进行大量计算(而且我说的是数百万甚至数十亿次),但这种差异几乎肯定无关紧要。 在绝大多数用户交互式应用程序中,所有计算机时间的99%都花在等待用户执行某些操作上。 我的建议是尽一切可能让你的生活变得更容易,如果(并 ...
  • 这只意味着其中一个利益在另一端没有相关的职位。 很可能它被删除了。 这可以通过以下方式防止: class Post < ActiveRecord::Base has_many :interests, :dependent => :destroy end 同时你应该清理数据库中的孤儿。 编辑:你声称这已经在你的模型中,但如果是这样,那么你不清楚如何可以有一个孤儿的兴趣,如错误所示。 也许它是在添加依赖子句之前创建的? 再次,通过SQL删除孤儿,然后再试一次。 如果稍后问题重新出现,则必须在不带回调的情况 ...
  • 您的基准测试不是比较相同的功能。 _render一个用字符串渲染1000个部分,_if_clause仅在比较时进行。 您应该比较例如模板渲染与内联通知处理和在部分中执行通知处理的模板。 但即使部分渲染速度要慢得多,另外需要考虑的是,它是否重要? 如果代码更容易理解,根据您的整体性能需求,可能值得牺牲一些毫秒的查看时间。 Your benchmark is not comparing the same functionality. The _render one is rendering 1000 parti ...
  • 部分恰好是较大表示层的部分位。 部分可以是菜单,其可以在许多页面(或布局的一部分)上重复使用。 在大多数情况下,帮助程序用于准备将要呈现的数据(例如,部分)。 部分“菜单”可以使用帮助程序,确保菜单中使用的每个URL都被删除双斜杠(“example.org/page/somevar/someval//otherval”)。 A partial is exactly that, a partial bit of the larger presentation layer. A partial could be ...
  • 示例1:您正在渲染部分x次(取决于事件)。 这意味着你正在编译html x次(每次循环运行一次)。 这很慢 示例2:您正在使用html编译一次的事件集合呈现一个部分(因为只有一个部分)。 这很快 example 1: you are rendering a partial x times (depending on events). which means you are compiling html x times(once each time the loop runs). which is slow ...
  • 我在使用-Xprint运行scalac之后的猜测-Xprint:all是在queue match { case Queue((thing, stuff), _*) => doThing(queue.tail) }的patmat结束时queue match { case Queue((thing, stuff), _*) => doThing(queue.tail) }示例我看到以下方法是叫(为简洁而编辑): val o9 = scala.collection.immutable.Queue.unapplyS ...

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。