【经验】Python3|输入多个整数(map方法或ctypes调用C标准库scanf)
生活随笔
收集整理的這篇文章主要介紹了
【经验】Python3|输入多个整数(map方法或ctypes调用C标准库scanf)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 方法一:多次調用input
- 1. 代碼
- 方法二:調用C標準庫
- 1. 代碼
- 2. 殘留的問題(int數組取元素)
- 附:計算時間差的程序(使用實例)
- 第一種讀取方式:
- 第二種讀取輸入方式:
方法一:多次調用input
1. 代碼
a = list(map(int,input().split(" ")))
方法來源:python怎么在鍵盤上一次輸入多個整數
方法二:調用C標準庫
1. 代碼
from ctypes import *
# Windows下:
libc = cdll.msvcrt
# Linux下: libc = CDLL("libc.so.6")
msg = [c_int(),c_int()]
libc.scanf(b"%d%d", byref(msg[0]),byref(msg[1]))
print(msg[0].value,msg[1].value)
參考:ctypes — Python 的外部函數庫官網的“傳遞指針(或以引用方式傳遞形參)”。
c_int()初始化變量,byref()取地址(相當于&符號)。
官方文檔:ctypes.pointer和ctypes.byref都可以進行取地址,但是ctypes.pointer會創建指針對象,操作更多。像使用c語言中的scanf來獲取輸入,就需要存儲地址,使用byref就足夠了。
注意:所有的字符串都要用二進制的字符串,也就是前面要加個
b。
2. 殘留的問題(int數組取元素)
理論上,用ctypes的int數組會更正確一些,但是我沒辦法取到int數組的后面的地址。
注意:通過value方法獲取值、用msg[0]獲取元素只適用于字符數組,對于int數組,msg[0]得到的就是value……麻,太不合理了。
如:msg = (c_int()*2)(999,888),msg[0]并不是數組第一個元素,而是第一個值999。我已經麻了,真查不到。如果有查到怎么取數組元素的朋友,請在評論區告訴我該怎么做qwq。
附:計算時間差的程序(使用實例)
第一種讀取方式:
import datetime
def showTime(now,level):
Str=""
if(level==1):
Str=str(now.hour)+':'+str(now.minute)
print(Str)
# 間隔數組,年-月-日-時-分-秒-毫秒,數組單位,顯示級別
def timeInterval(interval,begin_y=2010,begin_m=1,begin_d=1,begin_hh=0, begin_mm=0,begin_s=0,begin_ms=0,unit=1,level=1):
now=datetime.datetime(begin_y,begin_m,begin_d,begin_hh, begin_mm,begin_s,begin_ms)
showTime(now,level)
for any in a:
now=now + datetime.timedelta(minutes=any)
showTime(now,level)
begin_h, begin_m=list(map(int,input("起始:").split(" ")))
a=list(map(int,input("間隔:").split(" ")))
timeInterval(a, begin_hh=begin_h, begin_mm=begin_m)
第二種讀取輸入方式:
import datetime
def showTime(now,level):
Str=""
if(level==1):
Str=str(now.hour)+':'+str(now.minute)
print(Str)
# 間隔數組,年-月-日-時-分-秒-毫秒,數組單位,顯示級別
def timeInterval(interval,begin_y=2010,begin_m=1,begin_d=1,begin_hh=0, begin_mm=0,begin_s=0,begin_ms=0,unit=1,level=1):
now=datetime.datetime(begin_y,begin_m,begin_d,begin_hh, begin_mm,begin_s,begin_ms)
showTime(now,level)
for any in a:
now=now + datetime.timedelta(minutes=any)
showTime(now,level)
from ctypes import *
# Windows下:
libc = cdll.msvcrt
# Linux下: libc = CDLL("libc.so.6")
print("起始:",end='')
begin_h, begin_m = [c_int(),c_int()]
libc.scanf(b"%d%d", byref(begin_h),byref(begin_m))
a=list(map(int,input("間隔:").split(" ")))
timeInterval(a, begin_hh=begin_h.value, begin_mm=begin_m.value)
運行結果:
總結
以上是生活随笔為你收集整理的【经验】Python3|输入多个整数(map方法或ctypes调用C标准库scanf)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C#网络编程(六)----Socket编
- 下一篇: CentOS 7.6安装nginx