kunal sharma - 11 months ago 77

Python Question

**I have written code to take input as list of string**

`d=["","","","","","","","","",""]`

i=0

while(True):

s=input()

d[i]=s

i=i+1

if s=="":

break

but i am not able to process list 'd' to obtain required output

d[0] is storing "Djokovic:Murray:2-6,6-7,7-6,6-3,6-1" now i want to process this string(Either converting into dictionary)

Now i am able write code(by using str.split(",") function) to calculate Number of best-of-5 set matches won, Number of best-of-3 set matches won, Number of sets won, Number of games won, Number of sets lost, Number of games lost

Now i had stored result in dictionary as

playerStats={'Murray':[2,2,16,143,13,142],'Djokovic':[3,1,13,142,16,143],'Muguruza':[0,0,1,12,2,15],'Williams':[0,1,2,15,1,12]}

Now i want to

Djokovic 3 1 13 142 16 143

Murray 2 2 16 143 13 142

Williams 0 1 2 15 1 12

Muguruza 0 0 1 12 2 15

where criteria 1-6 are... 1. Number of best-of-5 set matches won 2. Number of best-of-3 set matches won 3. Number of sets won 4. Number of games won 5. Number of sets lost 6. Number of games lost

`playerNames=['Djokovic','Williams','Muguruza','Murray']`

n=0

if playerStats[playerNames[n]][0]>playerStats[playerNames[n+1]][0] and playerStats[playerNames[n]][0]>playerStats[playerNames[n+2]][0] and playerStats[playerNames[n]][0]>playerStats[playerNames[n+3]][0]:

print(playerNames[n],playerStats[playerNames[n]][0],playerStats[playerNames[n]][1],playerStats[playerNames[n]][2],playerStats[playerNames[n]][3],playerStats[playerNames[n]][4],playerStats[playerNames[n]][5])

if playerStats[playerNames[n+1]][0]>playerStats[playerNames[n+2]][0] and playerStats[playerNames[n+1]][0]>playerStats[playerNames[n+3]][0]:

print(playerNames[n+1],playerStats[playerNames[n+1]][0],playerStats[playerNames[n+1]][1],playerStats[playerNames[n+1]][2],playerStats[playerNames[n+1]][3],playerStats[playerNames[n+1]][4],playerStats[playerNames[n+1]][5])

if playerStats[playerNames[n+1]][0]>playerStats[playerNames[n+2]][0] and playerStats[playerNames[n+1]][0]>playerStats[playerNames[n]][0] and playerStats[playerNames[n+1]][0]>playerStats[playerNames[n+3]][0]:

print(playerNames[n+1],playerStats[playerNames[n]][0],playerStats[playerNames[n]][1],playerStats[playerNames[n]][2],playerStats[playerNames[n]][3],playerStats[playerNames[n]][4],playerStats[playerNames[n]][5])

Answer Source

Since your stats seem to be separated by a whitespace delimiter, you can use `str.split()`

to separate each of your stats into a list. here is a demo:

```
stats = "Djokovic:Murray:2-6,6-7,7-6,6-3,6-1 Murray:Djokovic:6-3,4-6,6-4,6-3"
def compile_stats(stats):
stats_lst = list(stats.split(" ")) # using str.split to
# split the string every time whitespace is found.
return stats_lst
print(compile_stats(stats))
# output:['Djokovic:Murray:2-6,6-7,7-6,6-3,6-1', 'Murray:Djokovic:6-3,4-6,6-4,6-3']
```

It takes each stat, and makes it its own separate list item.