This question already has answers here:
'str' object does not support item assignment [duplicate]
(10 answers)
Closed 10 months ago.
txt = "hello"
txt[0], txt[1] = txt[1], txt[0]
why doesn't this code work?
Isn't it similar to this?
a, b = 1,2
a,b = b,a
In Python, strings do not support the syntax str[num] = ... at all. The problem is not that you are trying to swap values, it is just that strings cannot be edited like that at all.
This question already has answers here:
Python append replaces the existing list with None
(2 answers)
Closed 1 year ago.
In the code below, it says it cannot append "a" because it is class NoneType but just before that line, it is able to print the list and print its type. Why does it lose its type on the next line?
from itertools import combinations_with_replacement
def output_list_of_feature_names(degree, list_of_feature_names):
a = ["as", "asd"]
for i in range(1, degree + 1):
for item in combinations_with_replacement(list_of_feature_names, r = i):
print(a)
print(type(a))
print(a)
a = a.append(item)
return a
output_list_of_feature_names(2, ["throttle", "angle", "final_vert_speed"])
a = a.append(item)
is the offending line. a.append is a function that modifies the list in-place and returns None. That return value is then assigned to a.
To fix, change to:
a.append(item)
This question already has answers here:
How do I count the occurrences of a list item?
(30 answers)
Closed 3 years ago.
I am working on a project, and an annoying thing is that when I print a list e.g.('a','a','a','b','c','b'), it will print:
a a a b c b
But, I would like it to join repeat values, e.g.:
a(3) b(2) c
I have a complicated function for doing this that still does not work(shown below) and does anyone have any suggestions?
def refine(testlist):
repeatfntest=0
prototypelist=testlist.copy()
lengthtest=len(testlist)-1
testlist.sort()
repititionfn=1
occurences=0
currentterm=prototypelist[lengthtest]
finalizedtermsfn=[]
while lengthtest>-1:
repititionfn=1
lengthtest=len(prototypelist)-1
occurences=0
while repititionfn>0:
lengthtest-=1
occurences+=1
print(currentterm)
prototypelist.remove(testlist[lengthtest])
if currentterm in prototypelist:
repititionfn=1
else:
repititionfn=0
if repititionfn==0 and occurences>1:
try:
finalizedtermsfn.append(str(currentterm)+"("+str(occurences)+")")
repititionfn=1
occurences=0
currentterm=prototypelist[lengthtest]
except:
print("Fail")
del finalizedtermsfn[-1]
elif repititionfn==0 and occurences==1:
try:
finalizedtermsfn.append(str(prototypelist[lengthtest]))
repititionfn=1
occurences=0
currentterm=prototypelist[lengthtest]
except:
print("Fail")
else:
currentterm=prototypelist[lengthtest]
return(finalizedtermsfn)
a=[6,0,1,1,1,1,1,2,2,2,2,4,4,4,5,5]
print(refine(a))
This Prints:
['5(2)','4(3)','2(4)','1(5)','6']
You can use collections.Counter with a list comprehension:
a=[6,0,1,1,1,1,1,2,2,2,2,4,4,4,5,5]
from collections import Counter
print(["%s(%d)"%(k,v) for k, v in Counter(a).items()])
#['0(1)', '1(5)', '2(4)', '4(3)', '5(2)', '6(1)']
If you want to avoid printing the 1 in parentheses for the single items, you can do:
print(["%s(%d)"%(k,v) if v > 1 else str(k) for k, v in Counter(a).items()])
#['0', '1(5)', '2(4)', '4(3)', '5(2)', '6']
This question already has answers here:
How can I select a variable by (string) name?
(5 answers)
Closed 8 months ago.
I would like to call multiple dictionaries using a for loop. I am unsure how to call multiple dictionaries properly, and I can't figure out if its possible using concatenation. The code below should explain my thinking even though the print statement is incorrect.
stat0 = {}
stat0["bob"] = 0
stat1 = {}
stat1["bob"] = 0
stat2 = {}
stat2["bob"] = 0
for i in range(3):
print(stat(i))
How about putting them in a collection, and then getting value generically:
for hm in [stat0, stat1, stat2]
print(hm["bob"])
Instead of naming your dictionaries, just put them into another dictionary:
#UNTESTED
stat = { 0: stat0, 1: stat1, 2: stat2 }
for i in range(3):
print(stat[i])
Or, use an iterative style more appropriate for dict:
#UNTESTED
for i, d in stat.items():
print(i, d)
This question already has answers here:
Converting list to nested dictionary
(4 answers)
Closed 5 years ago.
I have an issue that I've been trying to sort out. I have a string that needs to be converted to an nested dictionary with the keys and values based off the adjacent words in the string. Here is an example:
graphMaster = {}
inputSentence = "I have a dog named Max."
I would like to take this string, and convert it into a dictionary resembling the output below:
print graphMaster
{'I': {'have': {'a': {'dog': {'named': 'Max'}}}}}
I have tried the following:
graphMaster = {}
inputSentence = "I have a dog named Max."
while True:
inputList = inputSentence.strip().split(' ')
for currentIndex, word in enumerate(inputList):
nextIndex = currentIndex + 1
if nextIndex < len(inputList):
if word not in graphMaster.keys():
graphMaster[word] = inputList[nextIndex]
elif word in graphMaster.keys():
break
print graphMaster
I couldn't find a duplicate problem here and I pre-apologize if one exists that I couldn't find. Any help is greatly appreciated.
You could do something like this:
outdict = {}
curdict = outdict
for f in inputSentence.split(' '):
curdict[f] = {}
curdict = curdict[f]
print outdict
Where curdict is only pointing to a location in the output dictionary.