mport random x=[random.randint(0,200) for i in ra Python切片x【::2】=y怎么理解

\u5173\u4e8epython\u7684\u4e00\u4e2a\u95ee\u9898

import randomx=[random.randint (0,100) for i in range (1000)]print ("The random list is:\n",x)xset=set(x)#\u8f6c\u6362\u6210set\uff0c\u8fd9\u6837\u53ef\u4ee5\u53bb\u9664\u91cd\u590d\u6570\u636e\uff0c\u540e\u9762\u4e00\u53e5\u53ef\u4ee5\u5927\u5e45\u51cf\u5c11\u8ba1\u7b97\u91cfcounts=[(v,x.count(v)) for v in xset ]sorted_counts=sorted(counts,key=lambda x:(x[1],x[0]))print(counts)print ("The statistical result is:\n",sorted_counts)\u4e0d\u660e\u767d\u53ef\u8ffd\u95ee\u3002

[\u5f00\u59cb\u7d22\u5f15\uff1a\u7ed3\u675f\u7d22\u5f15\uff1a\u6b65\u957f]
\u4f8b\u5982x=[1\uff0c2\uff0c3\uff0c4\uff0c5\uff0c6],\u5219x[1::2]=[2,4,6]

\u7b2c\u4e00\u4e2a\u4f4d\u7f6e\u4e3a\u7a7a\uff0c\u9ed8\u8ba4\u4e3a0
\u7b2c\u4e8c\u4e2a\u4f4d\u7f6e\u4e3a\u7a7a\uff0c\u9ed8\u8ba4\u4e3a\u6700\u540e\u4e00\u4e2a\u5143\u7d20\u4f4d\u7f6e
\u7b2c\u4e09\u4e2a\u5143\u7d20\u4e3a\u7a7a\uff0c\u9ed8\u8ba4\u6b65\u957f\u4e3a1

为了更好的理解你的Python程序,我把Python程序做了注释,希望你能看明白.

完整的Python程序如下

import random  #引入随机函数库

x=[random.randint(0,200) for i in range(20)]  #产生20个[0-200]范围的随机数,并放到列表x中

print(x)  #打印列表x

y=x[::2]  #把列表x中,下标为偶数位置的数组成列表赋给y,相当于y=x[0:len(x)-1:2]

y.sort(reverse=True)  #把列表y中的数按照从大到小排序

x[::2]=y  #把排好序的列表y再赋给x的下标为偶数的位置,相当于x[0:len(x)-1:2]=y

print(x)  #打印列表x


运行结果
[108, 159, 175, 177, 101, 84, 88, 25, 164, 94, 199, 127, 153, 187, 11, 45, 113, 29, 10, 28]
[199, 159, 175, 177, 164, 84, 153, 25, 113, 94, 108, 127, 101, 187, 88, 45, 11, 29, 10, 28]


扩展阅读:xbox series x ... from random import ... www.sony.com.cn ... texas instruments ... python import random ... matebook14 ... hp elitebook 840 ... transport fever 2 ... random luck in universe ...

本站交流只代表网友个人观点,与本站立场无关
欢迎反馈与建议,请联系电邮
2024© 车视网