Static parameter count

T

Tertius Cronje

Hi all,
This does not feel Pythonic. Is there a better way to do the same?

Many TIA
T


# L = [1,2,3,4,5,6, etc....]
# L can contain 'n' elements
# fmt is made up to each particular specification

if len(L) == 0:
return ''
elif len(L) == 1:
return struct.pack(fmt,L[0] )
elif len(L) == 2:
return struct.pack(fmt,L[0] , L[1])
elif len(L) == 3:
return struct.pack(fmt,L[0] , L[1], L[2])
elif len(L) == 4:
return struct.pack(fmt,L[0] , L[1], L[2], L[3])
elif len(L) == 5:
return struct.pack(fmt,L[0] , L[1], L[2], L[3], L[4])
elif len(L) == 6:
return struct.pack(fmt,L[0] , L[1], L[2], L[3], L[4], L[5])

# etc... etc... etc ...
 
O

Ola Natvig

Tertius said:
Hi all,
This does not feel Pythonic. Is there a better way to do the same?

Many TIA
T


# L = [1,2,3,4,5,6, etc....]
# L can contain 'n' elements
# fmt is made up to each particular specification

if len(L) == 0:
return ''
elif len(L) == 1:
return struct.pack(fmt,L[0] )
elif len(L) == 2:
return struct.pack(fmt,L[0] , L[1])
elif len(L) == 3:
return struct.pack(fmt,L[0] , L[1], L[2])
elif len(L) == 4:
return struct.pack(fmt,L[0] , L[1], L[2], L[3])
elif len(L) == 5:
return struct.pack(fmt,L[0] , L[1], L[2], L[3], L[4])
elif len(L) == 6:
return struct.pack(fmt,L[0] , L[1], L[2], L[3], L[4], L[5])

# etc... etc... etc ...

return struct.pack(fmt, *L)

Should do the trick

ola
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,610
Members
45,255
Latest member
TopCryptoTwitterChannels

Latest Threads

Top