开发者

DRY version of a list

开发者 https://www.devze.com 2023-04-08 03:50 出处:网络
What would be the most efficient way to do the following: genres = [value_from_key(wb, \'Genre (1)\', n),

What would be the most efficient way to do the following:

genres = [value_from_key(wb, 'Genre (1)', n),
          value_from_key(wb, 'Genre (2)', n),
          value_from_key(wb, 'Genre (3)', n),
          value_from_key(wb, 'Genre (4)', n),]

I tried doing it with a list comprehension -- genres = [value_from_k开发者_StackOverflowey(wb, 'Genre (%s)'%(i), n) for i in range[1,4]], but it kept raising a TypeError saying object is unsubscriptable. What would be the DRY way of doing the above? Thank you.


Replace the square brackets [1,4] with round braces (1,4) in your call to range:

genres = [value_from_key(wb, 'Genre (%s)'%(i), n) for i in range(1,4)]


but it kept raising a TypeError saying object is unsubscriptable.

Because range[1,4] means "use the tuple (1, 4) as a subscript for range". Since range is a function, you want to call it, i.e. put the arguments in parentheses (just as you do for value_from_key). I don't really see how you would conclude from an error like this that there's something wrong with the list comprehension itself. o_O

What would be the DRY way of doing the above?

With the list comprehension.

0

精彩评论

暂无评论...
验证码 换一张
取 消