Python循环对项目进行乘法
我有一个很容易的问题,我真的不明白为什么会发生这种情况 我通过codewars网站学习Python。其中一个问题是将一个句子分开,并按包含每个单词的数字排序。例如,如果句子是Python循环对项目进行乘法,python,list,Python,List,我有一个很容易的问题,我真的不明白为什么会发生这种情况 我通过codewars网站学习Python。其中一个问题是将一个句子分开,并按包含每个单词的数字排序。例如,如果句子是“Matias3 I1 a2m”,程序应返回“I1 a2m Matias3”,因为包含每个单词的数字顺序不同 这是我正在使用的代码。这很简单,但当我分配新的顺序时,y[p]=…程序将寄存器相乘。如果我去掉那一行,寄存器就正常了,我不知道为什么 sentence="is2 Thi1s T4est 3a" #Example of
“Matias3 I1 a2m”
,程序应返回“I1 a2m Matias3”
,因为包含每个单词的数字顺序不同
这是我正在使用的代码。这很简单,但当我分配新的顺序时,y[p]=…
程序将寄存器相乘。如果我去掉那一行,寄存器就正常了,我不知道为什么
sentence="is2 Thi1s T4est 3a" #Example of sentence
x=sentence.split(" ") #I create an array with all the words
y= x #I create a second array (y). This is the one I will order by the numbers of the words
for i in range(len(x)): #I make a loop for the array x
print("i: "+str(i))
for j in range(len(x[i])): #I make a look for each character of the word
print(" i:"+str(i)+" j:"+str(j)+" "+x[i])
if x[i][j:j+1].isnumeric(): #If the character is a number, then Id like to put that word in the
#that number position in the y array (of course is the position-1)
p=int(x[i][j:j+1])-1 # This is the position that the word should be
y[p]=x[i] # When I assing y[] to the correct position (I want that the position i
# becomes the position p, the program get lost)
print(y)
如前所述,
y=x
为您提供了一个参考,而不是同一列表的副本。您需要执行y=x.copy()
以获得所需的结果
该行为在以下内容中进行了描述:
Python中的赋值语句不复制对象,而是在目标和对象之间创建绑定。对于可变的或包含可变项的集合,有时需要一个副本,以便可以在不更改另一个副本的情况下更改一个副本
但除此之外,此函数还提供以下结果:
print(sorted(sentence.split(), key=lambda e: min(e)))
正如您所看到的,已经有一个内置函数可以完成您想要的一切。您只需提供自己的排序功能。提供的排序函数搜索句子中单词的最小值。这是由内置函数完成的
要完成此任务,您必须执行最后一步:再次以字符串形式打印列表。这可以通过以下方式完成,请参阅:
@lain Shelvington所说的完全正确。但您可以尝试下面一些更具python风格的代码
sentence="is2 Thi1s T4est 3a"
raw_words_list = sentence.split(' ')
raw_words_dict = {}
for word in raw_words_list:
for char in word:
if char.isnumeric():
raw_words_dict[char] = word
print([raw_words_dict[key] for key in sorted(raw_words_dict.keys())])
y=x
不会生成第二个列表,它只会为您提供对同一列表的第二个引用。您对y
所做的任何更改都将发生在x
,y=x。copy()
将为您提供第二个列表
sentence="is2 Thi1s T4est 3a"
raw_words_list = sentence.split(' ')
raw_words_dict = {}
for word in raw_words_list:
for char in word:
if char.isnumeric():
raw_words_dict[char] = word
print([raw_words_dict[key] for key in sorted(raw_words_dict.keys())])