如何在python中检查数字是否在列表中
是否可以检查python中的列表中是否有某些数字?如果是,你怎么做 我的代码如下:如何在python中检查数字是否在列表中,python,list,Python,List,是否可以检查python中的列表中是否有某些数字?如果是,你怎么做 我的代码如下: listA=[[“钪”,15412830],“钛”,16683287],“钒”,19103407],“铬”,19072671],“锰”,12462061],“铁”,15382862],“钴”,14952870],“镍”,14552913],“铜”,10852562],“锌”,41953907]] listB=[[“thing”,999,333],“you”,444555]。#这只是为了测试代码 melt=int(
listA=[[“钪”,15412830],“钛”,16683287],“钒”,19103407],“铬”,19072671],“锰”,12462061],“铁”,15382862],“钴”,14952870],“镍”,14552913],“铜”,10852562],“锌”,41953907]]
listB=[[“thing”,999,333],“you”,444555]。#这只是为了测试代码
melt=int(输入(“所选元素的熔点是多少(摄氏度):”)
沸点=int(输入(“所选元素的沸点是多少(摄氏度):”)
如果在列表A中熔化:
对于listA中的w:
如果熔体==w[1]:
如果沸腾==w[2]:
打印(“是”,w[0],“您选择的元素?”)
如果熔融不在列表A中:
对于列表B中的x:
打印(x[0])#也仅用于测试目的
我输入了melt==1541
和boil==2830
,并期望输出钪是您选择的元素吗?
但是得到了
东西
你
相反,melt999
和BOOL333的输入(ish)用于测试目的
但是我如何检查给定的输入在哪个列表中并找出那个元素呢
提前谢谢
编辑强>
谢谢大家的帮助所有的答案都帮助了我,我把所有的建议(除了尝试,除了其他的
,除非有人想帮忙:D)都放进了我的作业代码(这个!)。所有答案都是正确的,但由于我只能标记一个,所以我标记了最上面的一个。再次感谢你 第一个条件是将单个值与列表进行比较。放下它,改用:
for w in listA:
if melt == w[1] and boil == w[2]:
print("Is", w[0], "your chosen element?")
break
与第二个条件不同(也有错误的比较),您可以向循环中添加一个else
子句(不要识别else
单词,因为它属于的第一个,而不是if
):
如果输入melt
时用户给出一个数字,例如1541,则变量melt
将包含一个整数1541。但是,元素的listA
包含3项、一个字符串和2个整数的列表
因此,当您测试melt
是否在listA
中时,它找不到任何东西,因为将1541
与[“钪”,15412830]
进行比较将返回False,因为两者不相等
此外,使用列表存储元素及其沸点并不理想。例如,很难访问元素沸点,因为它嵌套在列表中。字典实现,或者更好的数据帧实现(c.f.pandas)将更加高效
回到您的代码,这里有一个快速修复:
for w in listA:
if melt == w[1] and boil == w[2]:
print("Is", w[0], "your chosen element?")
最后,您还必须处理输入错误检查,以确认用户输入的数据有效
编辑:词典
使用dictionary,您可以将键链接到值。键和值可以是任何内容:数字、列表、对象、字典。唯一的条件是该键必须定义hash()
方法
例如,可以将字符串作为键存储元素,将两个温度作为值存储
elements = {"scandium": (1541, 2830), "titanium": (1668, 3287)}
要访问元素,您可以调用elements[“scandium”]
,它将返回(15412830)。您还可以使用3个功能访问字典的元素:
elements.keys()
:返回键
elements.values()
:返回值
elements.items()
:返回元组(键、值)
然而,再一次,单独获取温度并不容易。但这次你可以这样比较:
for key, value in elements.items():
if (melt, boil) == value:
print (key)
但更好的是,由于您是从熔化和沸腾温度查找元素,因此可以创建以下字典,其中键是元组(沸腾,熔化),值是对应的元素
elements = {(1541, 2830): "scandium", (1668, 3287): "titanium"}
然后,一旦用户输入了melt
和boil
,您就可以找到相应的元素:元素[(melt,boil)]
。这一次,不需要使用循环。可以直接访问相应的元素。
类似的实现可以通过一个数据帧来完成
最后,您还可以使用类来实现这一点
class Element:
def __init__(self, name, melt, boil):
self.name = name
self.melt = melt
self.boil = boil
elements = [Element("scandium", 1541, 2830), Element("titanium", 1668, 3287)]
实际上,元素
类不能用作字典的键。要将其用作键,必须定义散列
方法
class Element:
def __init__(self, name, melt, boil):
self.name = name
self.melt = melt
self.boil = boil
def __key(self):
return (self.name, self.melt, self.boil)
def __hash__(self):
return hash(self.__key())
但是,从melt
和boil
变量访问元素也不是那么简单。循环也是必要的。请参见下文(注意,代码的使用是为了提高可读性)
如果元素在少数列表中,则以下代码应起作用:
from collections import namedtuple
ElementProperties = namedtuple('ElementProperties', 'name melting_point boiling_point')
elements1 = [ElementProperties("scandium", 1541, 2830),
ElementProperties("titanium", 1668, 3287),
ElementProperties("vanadium", 1910, 3407),
ElementProperties("chromium", 1907, 2671),
ElementProperties("manganese", 1246, 2061),
ElementProperties("iron", 1538, 2862)]
elements2 = [ElementProperties("hydrogen", 5, 9)]
melt = int(input("What is the melting point of your chosen element (in degrees Celcius): "))
boil = int(input("What is the boiling point of your chosen element (in degrees Celcius): "))
found = False
for element_lst in [elements1,elements2]:
if found:
break
for element in element_lst:
if element.melting_point == melt and element.boiling_point == boil:
print('Your element is: {}'.format(element.name))
found = True
break
if not found:
print('Could not find element having melting point {} and boilong point {}'.format(melt, boil))
为了确保您的输入确实是数字,您可以这样做:
# Check input validity.
while True:
try:
melt = int(input("What is the melting point of your chosen element (in degrees Celcius): "))
boil = int(input("What is the boiling point of your chosen element (in degrees Celcius): "))
break
except ValueError:
continue
# Rest of the work.
...
基本上,在循环中,您要求用户输入。如果int()
成功,由于break
关键字,循环将退出,您可以放心地假设melt
和boil
是程序其余部分的整数。如果int() 在Aryerez所说的基础上,我将在开头添加一个ValueError
检查,以处理用户键入的不是数字的内容。@Guimoute抱歉,我在方面做得很差劲,除了我确信ValueError中涉及的其他内容之外。我不知道怎么做。有什么帮助吗…?是的,我会在这里把这项技术作为一个答案发布(不是,但是代码格式要好得多)。那么,else
是如何工作的呢?这只是我代码的一个片段,实际上我有更多的列表-准确地说是6个。else是否检查熔点和沸点是否不在此列表中
from collections import namedtuple
ElementProperties = namedtuple('ElementProperties', 'name melting_point boiling_point')
elements1 = [ElementProperties("scandium", 1541, 2830),
ElementProperties("titanium", 1668, 3287),
ElementProperties("vanadium", 1910, 3407),
ElementProperties("chromium", 1907, 2671),
ElementProperties("manganese", 1246, 2061),
ElementProperties("iron", 1538, 2862)]
elements2 = [ElementProperties("hydrogen", 5, 9)]
melt = int(input("What is the melting point of your chosen element (in degrees Celcius): "))
boil = int(input("What is the boiling point of your chosen element (in degrees Celcius): "))
found = False
for element_lst in [elements1,elements2]:
if found:
break
for element in element_lst:
if element.melting_point == melt and element.boiling_point == boil:
print('Your element is: {}'.format(element.name))
found = True
break
if not found:
print('Could not find element having melting point {} and boilong point {}'.format(melt, boil))
# Check input validity.
while True:
try:
melt = int(input("What is the melting point of your chosen element (in degrees Celcius): "))
boil = int(input("What is the boiling point of your chosen element (in degrees Celcius): "))
break
except ValueError:
continue
# Rest of the work.
...