社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
私信  •  关注

Siong Thye Goh

Siong Thye Goh 最近创建的主题
Siong Thye Goh 最近回复了
list1=['student1',10,20,40,'student2',20,20,40,'student3',20,30,40,'student4',20,10,30]
list2=[]
for i in range(0,len(list1),4):
    list2.append(list1[i])
    sum= list1[i+1]+list1[i+2]+list1[i+3]
    list2.append(sum)
print(list2)

生产

['student1', 70, 'student2', 80, 'student3', 90, 'student4', 60]

代码中的第二个for循环遍历列表中的每个元素,并在索引mod 4为1时执行操作。你不需要两个for循环。

7 年前
回复了 Siong Thye Goh 创建的主题 » 如何在python中为同一字符串添加相同的数字?

你可能想这样做:

准备一个字典,将字符串映射到一些标签号,并检查字符串是否存在。

object_map = {'Ball': 0, 'Square': 1}

def get_num_from_string(x):
    for i in object_map:
        if i in x:
            return object_map[i]

A = ['Check/Ball_red_move_01', 'Check/Square_jump_forward_01']

for i in A:
    print(i + ' '+str(get_num_from_string(i)))

这就产生了

Check/Ball_red_move_01 0
Check/Square_jump_forward_01 1

有几件事要考虑,你想做什么,没有一个字符串出现,也要做什么,如果多个字符串出现。

7 年前
回复了 Siong Thye Goh 创建的主题 » 尝试查找图像中黑色像素的百分比(python 2)

您的代码在Python3中运行良好。

我相信您的代码是用python 2编写的,其中two int的除法运算符产生一个int。这里有一个可能的解决方法。

def percentBlack(data):
    numB = 0
    numP = 0
    for line in data:
        for pixel in line:
            if pixel == "B":
                numB += 1
            numP += 1
    return round((numB * 100.0/numP),1)