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

方法一:多次调用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)

运行结果:在这里插入图片描述

posted @ 2022-04-19 12:11  shandianchengzi  阅读(2)  评论(0编辑  收藏  举报  来源