Python学习笔记1.25

思考题,练习题答案

1.怎样对python中的代码进行注释?
单行注释如#hello world 多行注释如 ''' hello world hello world ''' 或 """ hello world hello world hello world """
2.python有哪些运算符,这些运算符的优先级是怎样的?
算术运算符:+ - * / // % **
比较运算符:> >= < <= == !=
逻辑运算符: and or not
其他运算符: in not in is is not
运算符的优先级问题:
(1)一元运算符优于二元运算符
(2)先算术运算,后移位运算,最后位运算
(3)逻辑运算最后结合
3.python 中 is, is not 与 , != 的区别是什么?
(1)is, is not 对比的是两个变量的内存地址
(2)
, != 对比的是两个变量的值
(3)比较的两个变量,指向的都是地址不可变的类型(str等),那么is,is not 和 ==,!= 是完全等价的。
(4)对比的两个变量,指向的是地址可变的类型(list,dict等),则两者是有区别的。
4.python 中包含哪些数据类型?这些数据类型之间如何转换?

包含的数据类型: int float bool
数据类型之间的转换
#1 整数转化为列表:
number = 123
方法1:print([int(x) for x in str(number)])
方法2:list(str(number))
#2 列表转化为整数:
digits = [1, 2, 3]
print(str(int(''.join(str(item) for item in digits))))
#3 整数转换为字符串
digits = 123
s = str(digits)
#4 字符串转化为整数
s = "123"
a = int(s)
#5 列表转换为字符串
dataList = ['1', '2', '3', '4']
"".join(dataList)
dataList = str(dataList)
print(type(dataList), dataList)
#6 字符串转换为列表
str1 = "12345" # 逐个字母分开
list1 = list(str1)
print(list1)
str2 = "123 sjhid dhi" # 空格分开
list2 = str2.split() # or list2 = str2.split(" ")
print(list2)
str3 = "www.google.com" # 逗号分开
list3 = str3.split(".")
print(list3)
#7 元组 和 列表之间的转换
元组 转换成 列表
list(元组)
列表 转换成 元组
tuple(列表)
#8 列表反转为列表
list1 = [1, 2, 3]
方法1:   print(list(reversed(list1)))
方法2:  list.reverse(list1)
		print(list1)

练习题2

(1)使用count函数
class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        for i in range(len(nums)):
            if nums.count(nums[i]) < 2:
                return nums[i]
            else:
                continue
(2)删除递归
class Solution:
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        for i in range(len(nums)):
            this_num = nums.pop()
            if this_num not in nums:
                return this_num
            else:
                nums.remove(this_num)
(3)使用异或运算符
class Solution:
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        a = 0
        for num in nums:
            a = a ^ num
        return a
(4)使用位运算符
class Solution:
    def singleNumber(self,nums):
        a=0
        for num in nums:
            a=a^(1<<num)
        return a

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值