2

i have string like below :

FuntionStr='AccName,S,Balance,N,AccrInterest,N'

i would like to convert string to two dimensionals list :

FuntionList=[('AccName','S'),('Balance','N'),('AccrInterest','N')]

Please help give me any example code.

Regards,

Sovankiry
  • 135
  • 1
  • 14

3 Answers3

1

Your expected output is a list of tuples which you can get with zip, str.split and using iter which is more efficient than slicing.

FuntionStr='AccName,S,Balance,N,AccrInterest,N'
it = iter(FuntionStr.split(","))

print(list(zip(it,it)))
[('AccName', 'S'), ('Balance', 'N'), ('AccrInterest', 'N')]

If you have an uneven length list after splitting and you don't want to lose any data you can use zip_longest:

FuntionStr='AccName,S,Balance,N,AccrInterest,N,foo'
it = iter(FuntionStr.split(","))
from itertools import zip_longest
print(list(zip_longest(it, it,fillvalue="")))]
('AccName', 'S'), ('Balance', 'N'), ('AccrInterest', 'N'), ('foo', '')]
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
1

To get this:

FuntionStr='AccName,S,Balance,N,AccrInterest,N'
my_list = FuntionStr.split(',')
print my_list
print zip(my_list[::2], my_list[1::2])

OUTPUT:

[('AccName','S'),('Balance','N'),('AccrInterest','N')]
Stephen Lin
  • 4,852
  • 1
  • 13
  • 26
0

Try this

temp = FuntionStr.split(',')
>>>zip(temp[::2], temp[1::2])
[('AccName', 'S'), ('Balance', 'N'), ('AccrInterest', 'N')]
itzMEonTV
  • 19,851
  • 4
  • 39
  • 49