鱼C论坛

 找回密码
 立即注册
查看: 2965|回复: 17

[技术交流] Python:每日一题 145

[复制链接]
发表于 2018-1-24 09:58:29 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 jerryxjr1220 于 2018-1-25 09:37 编辑

我们的玩法做了一下改变:

1. 楼主不再提供答案。
2. 请大家先独立思考”,再参考其他鱼油的解答,这样才有助于自己编程水平的提高。
3. 鼓励大家积极答题,奖励的期限为出题后24小时内。
4. 根据答案的质量给予1~3鱼币的奖励。

题目:转换RBG颜色值
我们知道在网页中的颜色值设置都是用16进制的RGB来表示的,比如#FFFFFF,表示R:255,G:255,B:255的白色。

现在请设计一个函数可以转换RGB的16进制至10进制,或者转换10进制至16进制输出格式。

例:
print( color("#FFFFFF"))
>>>(255, 255, 255)
print( color((255,255,255))
>>> #FFFFFF

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2018-1-24 10:47:37 | 显示全部楼层
本帖最后由 BngThea 于 2018-1-24 17:01 编辑
  1. def color(c):
  2.     if isinstance(c,str):
  3.         col = []
  4.         for i in range(1,6,2):
  5.             col.append(eval('0x'+c[i:i+2]))
  6.         return(tuple(col))
  7.     else:
  8.         return('#'+((str(hex(c[0])))[-2:]).upper() + \
  9.                ((str(hex(c[1])))[-2:]).upper() + \
  10.                ((str(hex(c[2])))[-2:]).upper())
  11.    
  12. print(color('#FFFFFF'))
  13. print(color((255,255,255)))
复制代码

评分

参与人数 1荣誉 +3 鱼币 +3 贡献 +3 收起 理由
jerryxjr1220 + 3 + 3 + 3

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2018-1-24 10:57:23 | 显示全部楼层
  1. def color(c):
  2.     if (isinstance(c, tuple) or isinstance(c, list)) and len(c) == 3 and sum([isinstance(i, int) and  -1 < i < 256 for i in c]) == 3:
  3.         result = [hex(i)[2:].zfill(2).upper() for i in c]
  4.         return '#'+''.join(result)
  5.     elif isinstance(c, str):
  6.         c = c.upper()
  7.         if c[0] == '#' and len(c) == 7 and sum([i in '0123456789ABCDEF' for i in c[1:]]) == 6:
  8.             return (int(c[1:3], 16), int(c[3:5], 16), int(c[5:7],16))
  9.         else:
  10.             return '输入错误'
  11.     else:
  12.         return '输入错误'


  13. print(color((125, 125, 125)))
  14. print(color((255, 255, 255)))
  15. print(color(('a', 255, 255)))
  16. print(color((-1, 255, 255)))
  17. print(color((256, 255, 255)))
  18. print(color((0.1, 255, 255)))
  19. print(color((255, 255, 255, 255)))
  20. print(color('#FFFFFF'))
  21. print(color('#00FF0A'))
  22. print(color('#GFF000'))

  23. ##    输出:
  24. ##    #7D7D7D
  25. ##    #FFFFFF
  26. ##    输入错误
  27. ##    输入错误
  28. ##    输入错误
  29. ##    输入错误
  30. ##    输入错误
  31. ##    (255, 255, 255)
  32. ##    (0, 255, 10)
  33. ##    输入错误
复制代码

评分

参与人数 1荣誉 +3 鱼币 +3 贡献 +3 收起 理由
jerryxjr1220 + 3 + 3 + 3

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2018-1-24 11:53:33 | 显示全部楼层
  1. #! /usr/bin/env python
  2. # -*- coding: utf-8 -*-

  3. #RGB转换 给出#FFFFFF 返回[255,255,255]
  4. def rgb_16to10(str):
  5.         resRGB = [0,0,0]
  6.         resRGB[0]=int('0x'+str[1:3],16)
  7.         resRGB[1]=int('0x'+str[3:5],16)
  8.         resRGB[2]=int('0x'+str[5:7],16)
  9.         return resRGB

  10. #RGB转换 给出[255,255,255] 返回#ffffff
  11. def rgb_10to16(rgb):
  12.         r = hex(int(rgb[0]))
  13.         g = hex(int(rgb[1]))
  14.         b = hex(int(rgb[2]))
  15.         return '#'+r[2:4]+g[2:4]+b[2:4]
  16.        
  17. if __name__ == '__main__':
  18.         #RGB 16到10
  19.         print(rgb_16to10('#FFAABB'))
  20.         #RGB 10到16
  21.         print(rgb_10to16([255,240,233]))
复制代码


利用自带函数和字符串切片。不许笑。

评分

参与人数 1荣誉 +3 鱼币 +3 贡献 +3 收起 理由
jerryxjr1220 + 3 + 3 + 3

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2018-1-24 13:46:49 | 显示全部楼层
  1. def color(arg):
  2.     # 如果是字符串参数
  3.     if(type(arg) == str):
  4.         hexcolor = int(arg.replace('#',''), 16)
  5.         tuplecolor = (hexcolor >> 16, 0xff & (hexcolor >> 8), 0xff & hexcolor )
  6.         return tuplecolor
  7.     # 如果是元组参数
  8.     elif(type(arg) == tuple):
  9.         # 移位操作
  10.         intcolor = arg[0] << 16
  11.         intcolor += arg[1] << 8
  12.         intcolor += arg[2]
  13.         hexcolor = hex(intcolor)
  14.         strcolor = ''
  15.         if arg[0] == 0:
  16.             strcolor = "#00"
  17.             strcolor += hexcolor.replace('0x','').upper()
  18.         else:
  19.             strcolor = hexcolor.replace('0x','#').upper()
  20.         return strcolor


  21. print(color('#123456'))
  22. print(color((0, 255, 128)))
复制代码

评分

参与人数 1荣誉 +3 鱼币 +3 贡献 +3 收起 理由
jerryxjr1220 + 3 + 3 + 3

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2018-1-24 19:26:35 | 显示全部楼层

  1. def RGB2HEX(rgb):
  2.    
  3.    
  4.     hexcolor = '#%X%X%X' % rgb

  5.    

  6.     return hexcolor
  7.    
  8.    
  9.    
  10.    
  11. def HEX2RGB(hexcolor):
  12.     if len(hexcolor)!=7 or hexcolor[0]!="#":
  13.         print("please input the hexcolor like '#rrggbb'")
  14.     else:
  15.         r= hexcolor[1:3]
  16.         g= hexcolor[3:5]
  17.         b= hexcolor[5:]
  18.         rc,gc,bc= int(r,16),int(g,16),int(b,16)
  19.         return(rc,gc,bc)
复制代码

评分

参与人数 1荣誉 +3 鱼币 +3 贡献 +3 收起 理由
jerryxjr1220 + 3 + 3 + 3

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2018-1-24 22:10:31 | 显示全部楼层
  1. def convert_color(color):
  2.     hex2dec = {'0': 0, "1": 1, "2": 2, "3": 3, '4': 4, "5": 5, '6': 6, '7': 7, '8': 8, '9': 9, 'A': 10, 'B': 11, "C": 12,
  3.                "D": 13, 'E': 14, 'F': 15}
  4.     if isinstance(color, str):
  5.         red = hex2dec[color[1]] * 16 + hex2dec[color[2]]
  6.         green = hex2dec[color[3]] * 16 + hex2dec[color[4]]
  7.         blue = hex2dec[color[5]] * 16 + hex2dec[color[6]]

  8.         return red, green, blue
  9.     else:
  10.         hex_color = '#'
  11.         for each in color:
  12.             hex_color += hex(each)[2:].rjust(2, '0')
  13.         return hex_color.upper()
复制代码

评分

参与人数 1荣誉 +3 鱼币 +3 贡献 +3 收起 理由
jerryxjr1220 + 3 + 3 + 3

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2018-1-24 22:46:09 | 显示全部楼层
  1. def color(c):
  2.     try:
  3.         if c[0]=='#':
  4.             dict1={'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,\
  5.                    '9':9,'A':10,'B':11,'C':12,'D':13,'E':14,'F':15}
  6.             R=dict1[c[1].upper()]*16+dict1[c[2].upper()]
  7.             G=dict1[c[3].upper()]*16+dict1[c[4].upper()]
  8.             B=dict1[c[5].upper()]*16+dict1[c[2].upper()]
  9.             return (R,G,B)
  10.         elif len(c)==3:
  11.             list1=['0','1','2','3','4','5','6','7',\
  12.                    '8','9','A','B','C','D','E','F']
  13.             R=list1[c[0]//16]+list1[c[0]%16]
  14.             G=list1[c[1]//16]+list1[c[1]%16]
  15.             B=list1[c[2]//16]+list1[c[2]%16]
  16.             return '#'+R+G+B
  17.         else:return '输入有误'
  18.     except:
  19.         return '输入有误'
复制代码

评分

参与人数 1荣誉 +3 鱼币 +3 贡献 +3 收起 理由
jerryxjr1220 + 3 + 3 + 3

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2018-1-26 11:53:06 | 显示全部楼层
  1. def color(x):

  2.     def dec_to_hex(y):
  3.         list_a = '0123456789ABCDEF'
  4.         return '%s%s'%(list_a[y//16],list_a[y%16])

  5.     if x[0] == '#':
  6.         return (int(x[1:3],16),int(x[3:5],16),int(x[5:7],16))
  7.     return '#%s%s%s'%(dec_to_hex(x[0]),dec_to_hex(x[1]),dec_to_hex(x[2]))
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2018-2-2 15:28:28 | 显示全部楼层
本帖最后由 天圆突破 于 2018-2-2 15:30 编辑
  1. def color(*args):
  2.     value= [x for x in args]
  3.     if len(value) == 3:
  4.         a,b,c = value
  5.         try:
  6.             if 0 <= int(a) <= 255 and 0 <= int(b) <= 255 and 0 <= int(c) <= 255:
  7.                 return  '#' + hex(a)[2:].upper() + hex(b)[2:].upper() + hex(c)[2:].upper()
  8.             else:
  9.                 print('请输入一个正确的10进制RBG值。')
  10.         except:
  11.             print('请输入一个正确的10进制RBG值。')
  12.     elif len(value) == 1 and (len(str(value[0])) == 6 or len(str(value[0])) == 7 and (str(value[0]))[0] == '#'):
  13.         if len(str(value[0])) == 7:
  14.             a,b,c = (str(value[0]))[1:3],(str(value[0]))[3:5],(str(value[0]))[5:7]
  15.         else:
  16.             a,b,c = (str(value[0]))[0:2],(str(value[0]))[2:4],(str(value[0]))[4:6]
  17.         try:
  18.             a = int(a,16);b = int(b,16);c = int(c,16)
  19.             return (a,b,c)
  20.         except:
  21.             print('输入错误,请输入一个正确的16进制RGB值。')
  22.     else:
  23.         print('请输入一个正确的RGB数字。')

  24. print(color('#123456'))
  25. print(color(123,232,156))
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2018-2-2 18:33:51 | 显示全部楼层
  1. def color(obj):
  2.     try:
  3.         return "#{:X}{:X}{:X}".format(*obj)
  4.     except ValueError:
  5.         return tuple(int(obj[i:i+2], 16) for i in range(1, 6, 2))
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2018-2-4 10:40:34 | 显示全部楼层
本帖最后由 被翻红浪 于 2018-2-4 10:45 编辑
  1. def hex2dec(n):
  2.     numDic = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15}
  3.     r = numDic[n[1]] * 16 + numDic[n[2]]
  4.     g = numDic[n[3]] * 16 + numDic[n[4]]
  5.     b = numDic[n[5]] * 16 + numDic[n[6]]
  6.     print("%d, %d, %d" % (r, g, b))


  7. def dec2hex(*n):
  8.     r, g, b = n
  9.     red = convert(r)
  10.     green = convert(g)
  11.     blue = convert(b)
  12.     print("#"+ red + green + blue)


  13. def convert(n):
  14.     result = ""
  15.     digits = "0123456789ABCDEF"
  16.     if n == 0:
  17.         result = 0
  18.     else:
  19.         while n != 0:
  20.             temp = n % 16
  21.             n //= 16
  22.             result += digits[temp]

  23.     return str(result)[::-1]
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2018-2-5 09:17:34 | 显示全部楼层
  1. def color(a):
  2.     if type(a)==str:
  3.         RGB=[a[1:3],a[3:5],a[5:7]]
  4.         RGB_num=[]
  5.         for i in RGB:
  6.             RGB_num.append(int(i,16))
  7.         return tuple(RGB_num)
  8.     if type(a)==tuple:
  9.         RGB_str='#'
  10.         for i in a:
  11.             RGB_str+=hex(i)[2:]
  12.         return RGB_str.upper()
  13. print(color('#FFFFFF'))
  14. print(color((255,255,255)))
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2018-2-13 13:02:48 | 显示全部楼层
  1. def color(s):
  2.     if isinstance(s, str) and s.startswith("#"):
  3.         return(tuple([int(x,16) for x in [s[1:3],s[3:5],s[5:7]]]))
  4.     elif isinstance(s, tuple):
  5.         return("#%X%X%X"%(s[0],s[1],s[2]))
复制代码


  1. print(color("#FFFFFF"))
  2. print(color("#F2F4EF"))
  3. print(color((255, 255, 255)))
  4. print(color((0, 0, 0)))

  5. (255, 255, 255)
  6. (242, 244, 239)
  7. #FFFFFF
  8. #000
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2018-3-29 18:50:27 | 显示全部楼层
  1. import re


  2. def color(string):
  3.     if isinstance(string, str):
  4.         result = re.match(r'#[a-fA-F]{6}', string)
  5.         if result != None:
  6.             result = result.string[1:]
  7.             return tuple(eval('({0},{1},{2})'.format(int(result[0:2], 16), int(result[2:4], 16), int(result[4:6], 16))))
  8.     elif isinstance(string, tuple):

  9.         result = re.findall(r"\d{1,3}", string.__str__())
  10.         if result != None:
  11.             return "#{0}{1}{2}".format(hex(int(result[0]))[2:], hex(int(result[1]))[2:], hex(int(result[2]))[2:])
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2018-5-9 00:05:00 | 显示全部楼层
def color(list_str):
    if type(list_str) == str:
        out_list = []
        for i in range(3):
            a = list_str[i+1:i+3]
            b = int(a, base = 16)
            out_list.append(b)
        return "({0},{1},{2})".format(out_list[0],out_list[1],out_list[2])
    elif type(list_str) == tuple:
        a = ""
        for i in range(len(list_str)):
            a += "%x"%list_str[i]
            #print(a.upper())
        return "#"+a.upper()
    else:
        pass
   
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-1-8 22:34:35 | 显示全部楼层
  1. colorValue = input('请输入颜色值:')

  2. dic = {
  3.         'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15,
  4.         'a': 10, 'b': 11, 'c': 12, 'd': 13, 'e': 14, 'f': 15
  5. }
  6. dic1 = {
  7.         10: 'A', 11: 'B', 12: 'C', 13: 'D', 14: 'E', 15: 'F'
  8. }

  9. def conToTen(array):
  10.         tempList = array[:]
  11.         for i in tempList:
  12.                 if i == '#':
  13.                         array.remove(i)
  14.         tempList.clear()
  15.         for i in range(6):
  16.                 if i % 2 == 1:
  17.                         temp = []
  18.                         temp.append(array[i - 1])
  19.                         temp.append(array[i])
  20.                         tempList.append(temp)
  21.         temp = []
  22.         for i in tempList:
  23.                 tempNum = 0
  24.                 for j in range(2):
  25.                         tempNum1 = 0
  26.                         if i[j] in dic:
  27.                                 tempNum1 += dic[i[j]] * (16 ** (1 - j))
  28.                         else:
  29.                                 tempNum1 += int(i[j]) * (16 ** (1 - j))
  30.                         tempNum += tempNum1
  31.                 temp.append(tempNum)
  32.         print(temp)

  33. def conToSixteen(array):
  34.         tempStr = ''.join(array)
  35.         tempList = tempStr.split(',')
  36.         SList = ['#']
  37.         for i in tempList :
  38.                 i = int(i)
  39.                 if i > 255 :
  40.                         print('输入的值过大...')
  41.                         break
  42.                 else :
  43.                         if (i // 16 > 9) and (i % 16 > 9) :
  44.                                 SList.append(dic1[i // 16])
  45.                                 SList.append(dic1[i % 16])
  46.                         elif (i // 16 > 9) and (i % 16 <= 9) :
  47.                                 SList.append(dic1[i // 16])
  48.                                 SList.append(str(i % 16))
  49.                         elif (i // 16 <= 9) and (i % 16 > 9) :
  50.                                 SList.append(str(i // 16))
  51.                                 SList.append(dic1[i % 16])
  52.                         else :
  53.                                 SList.append(str(i // 16))
  54.                                 SList.append(str(i % 16))
  55.         print(''.join(SList))

  56. def confirmValue(inputValue):
  57.         list1 = list(str(inputValue[:]))
  58.         temp = inputValue.split(',')
  59.         if len(temp) > 1 :
  60.                 conToSixteen(list1)
  61.         else :
  62.                 conToTen(list1)


  63. confirmValue(colorValue)
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-8-18 22:46:46 | 显示全部楼层
  1. def func(n):k=hex(n)[2:];return k if len(k)==2 else '0'+k
  2. def color(th,ch=1):#ch为真则转换为代码,否则转换为数字
  3.         if ch:
  4.                 if type(th)not in tuple,list:raise TypeError
  5.                 if len(th)!=3:raise ValueError
  6.                 for i in th:
  7.                         if type(i)!=int:raise TypeError
  8.                         if not 255>=i>=0:raise ValueError
  9.                 return '#'+func(th[0])+func(th[1])+func(th[2])
  10.         else:
  11.                 if type(th)!=str:raise TypeError
  12.                 th.lstrip('#')
  13.                 if not th.isdigit or len(th)!=6:raise ValueError
  14.                 return (int(th[:2],16),int(th[2:4],16),int(th[4:],16))
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-3-29 17:14

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表