+ 3

List String To List Name

Say I Have: import random rint=random.randint list=["ABC","BCD","CDE"] ABC=["1", "2"," 3"] main=list[rint(0,0)#Usually Would Be 0,2 but to make example easy to understand it will be 0,0 sub=main[rint(0,0)] print(main)#Prints out "ABC" print(sub)#Prints out "A" Output is: A Wanted Output: 2 How can I get the output as "1" from the list ABC instead of "A" from the list item? Sorry if it doesn't make sense I don't really know how to explain it that well.

19th Mar 2017, 6:46 PM
MemeSenpai
MemeSenpai - avatar
6 Respostas
+ 9
# There's many ways to do it, with nested list in dict ( I guess your first list contain other same kind of name lists ): list = ["ABC","BCD","CDE"] dict = {"ABC":["1","2","3"],"BCD":["4","5"],"CDE":["6","7"]} x = dict[list[0]] print(x[1]) # ... and, if you want to lighten notation, use a function: _list = ["ABC","BCD","CDE"] dict = {"ABC":["1","2","3"],"BCD":["4","5"],"CDE":["6","7"]} def list(index): global dict return dict[list[index]] x = list(0) print(x[1]) # ( according to your needs, you can use global and/or local variables, obviously ^^ )
19th Mar 2017, 9:16 PM
visph
visph - avatar
+ 7
I'm happy if this help: I've seen only after you've updated your question ^^ Be carreful: as I read too fast first your new example code, I didn't see that you define a 'rint' custom variable with the 'randint' function, so while searching what would do this function on internet, I find that a rint() function exists in numpy library... It doesn't matter a lot, but you need to know that if you'll have to use this module ;)
19th Mar 2017, 9:26 PM
visph
visph - avatar
+ 1
if you want x to have the values of ABC then have x = ABC rather than x = list. Or maybe I'm misunderstanding the question.
19th Mar 2017, 8:16 PM
Jason Williams
Jason Williams - avatar
+ 1
@Jason Williams Yes, it seems you misunderstood my question but now I've updated it
19th Mar 2017, 9:02 PM
MemeSenpai
MemeSenpai - avatar
+ 1
Thank You Very Much @visph I've been trying to figure this out for so long (since this morning :P) Thank You Very Much For The Spread Of Your Knowledge And Your Amazing Solution!
19th Mar 2017, 9:19 PM
MemeSenpai
MemeSenpai - avatar
- 1
list = ["ABC","BCD","CDE"] dict = {"ABC":["1","2","3"],"BCD":["4","5"],"CDE":["6","7"]} x = dict[list[0]] print(x[1]) # ... and, if you want to lighten notation, use a function: _list = ["ABC","BCD","CDE"] dict = {"ABC":["1","2","3"],"BCD":["4","5"],"CDE":["6","7"]} def list(index): global dict return dict[list[index]] x = list(0) print(x[1])
19th Mar 2017, 10:41 PM
Tanmay Doneria
Tanmay Doneria - avatar