开发者

Distributing list items to variables in python

I'm fairly new to Python and I'm looking for a way to distribute items in a list into individual variables. The point of this is to display individual items as text objects in Blender. Here's what I have so far, but I know there's gotta be a more efficient way to go about doing this.

file = open('lyrics.conf')
data = file.read()
file.close()
b = data.split('/')
v = len(b)

if v >= 1:
  v1 = b[0]
if v >= 2:
  v2 = b[1]
if v >= 3:
  v3 = b[2]
if v >= 4:
  v4 = b[3]
if v >= 5:
  v5 = b[4]
if v >= 6:
  v6 = b[5]
if v >= 7:
  v7 = b[6]
if v >= 8:
  v8 = b[7]
if v >= 9:
  v9 = b[8]
if v >= 10:
  开发者_C百科v10 = b[9]


if you really want individual variables, at some point you have at least to do an unpacking like v1,v2,v3,v4,v5,v6,v7,v8,v9,v10 = some_list

but why would you want to do this? if something is a collection/list of things, it is best represented as such.


With b you already have an easily accessible list of the items you want. Just access them, when you need them at their indices b[0], b[1], .... Populating the namespace with too many variables, whose values can, without major problems, be stored in a container, is a design flaw (in my eyes).


Here's a way to inject new variables into the current modules namespace, but it's evil:

#!/usr/bin/env python

import sys

somelist = range(10)

for i, item in enumerate(somelist):
    setattr(sys.modules[__name__], 'v{0}'.format(i), item)

print v1 + v2
# => 3

print v1 * v2 * v3 * v4 * v5 * v6 - v7 * v8 - v9 + 11
# => ...


Having these v1..10 variables seems like a code smell to me, but you can try this

try:
  v1 = b[0]
  v2 = b[1]
  v3 = b[2]
  v4 = b[3]
  v5 = b[4]
  v6 = b[5]
  v7 = b[6]
  v8 = b[7]
  v9 = b[8]
  v10 = b[9]
except IndexError:
  pass


To process a list of verses, verse by verse:

with open('lyrics.conf') as f:
    data = file.read()
verses = data.split('/')
def build_blender_object(verse):
  # Put meaningful code here
  pass
blender_objects = [build_blender_object(v) for v in verses]

Then do whatever you want with the blender objects. If the position in the list matters, then you can use enumerate() to associate an index with each blender object.


Just for fun

b = "Some text/ with a / slash / character".split('/')
for i in range(len(b)):
    globals()['v' + str(i + 1)] = b[i]


Is it acceptable for the variables to exist and be set to None?

v1,v2,v3,v4,v5,v6,v7,v8,v9,v10 = (b+[None]*10)[:10]

or

v1,v2,v3,v4,v5,v6,v7,v8,v9,v10 = b+[None]*(10-len(b))
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜