Reputation: 25
I'm currently learning really basic python as a side project during my PhD. And to apply what I'm learning, I wanted to automate a basic sudoku grid solver.
This story begins with a list...
lines=['53xx7xxxx', '6xx195xxx', 'x98xxxx6x', '8xxx6xxx3', '4xx8x3xx1', '7xxx2xxx6', 'x6xxxx28x', 'xxx419xx5', 'xxxx8xx79']
And I'd like to get something that looks like:
line1=['5', '3', 'x', 'x', '7', 'x', 'x', 'x', 'x']
line2=['6', 'x', 'x', '1', '9', '5', 'x', 'x', 'x']
...
etc...
What I've been struggling with is looping the whole thing in a very efficient way. For now what i've done is creating each list by taking each elements and then split them with a small function I saw somewhere on a tutorial website.
For each element in the list, i repeat that, I just need to copy paste and get line1 to line9 lists.
def split(word):
return [char for char in word]
line1=lines[0]
line1=split(line1)
line2=lines[1]
line2=split(line2)
...
It works, but it does look not efficient at all. I did not find any beginner-friendly anwser yet for this specific question.
Do you guys know a better way to handle multiple list generation inside loops?
Thanks for your attention, Enjoy your day!
(PS: i'm french, sorry for any english related mistakes!)
Upvotes: 1
Views: 49
Reputation: 46
You could iterate through your list using a for-loop, split the element using your split method and store the split elements in a new List. By iterating through that new list you can access the splitted lines again.
Here is a little example. The first print command will print out the entire List. The second one a single element.
def split(word):
return [char for char in word]
newList = []
for line in lines:
line = split(line)
newList.append(line)
print(newList)
print(newList[0])
Upvotes: 2
Reputation: 557
Python provides direct typecasting of string into list using list(). You can use this function instead:
def split(word):
return list(word)
Upvotes: 1