日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【经验】Python3|输入多个整数(map方法或ctypes调用C标准库scanf)

發布時間:2025/5/22 编程问答 42 如意码农
生活随笔 收集整理的這篇文章主要介紹了 【经验】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.pointerctypes.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)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。