简体   繁体   English

Python简单程序遍历列表

[英]Python Simple program iteration through list

I'm new to programming and I'm making a simple program to test. 我是编程新手,正在制作一个简单的程序进行测试。 Here is the code: 这是代码:

list1 = [1,2,d,,t,h,7,8]

for x in list1:
    if x == 

I'm trying to iterate in my list and check to see which item is a string and which is a number(I know its basic, but im new). 我试图在我的列表中进行迭代,并检查哪个项目是字符串,哪个项目是数字(我知道它的基本知识,但我是新的)。 So what would be a correct way to write this line of code. 那么编写这行代码的正确方法是什么。 All suggestions would help 所有建议都会有所帮助

In Python, use the builtin isinstance(variable, type) to test whether a variable is of a given type. 在Python中,使用内置的isinstance(variable, type)来测试变量是否为给定类型。

The type variable can also be a tuple of several types to test against. type变量也可以是要测试的几种类型的元组。

Your list is a little messed up. 您的清单有些混乱。 If those letters are supposed to be strings, it should look like this: 如果这些字母应该是字符串,则应如下所示:

list1 = [1,2,'d','t','h',7,8]

Otherwise they are referring to variables. 否则,它们是指变量。

To check if number 检查号码

for x in list1:
    if isinstance(x, int):
        ...

To check if string 检查字符串是否

for x in list1:
    if isinstance(x, str):
       ...

Combination 组合

for x in list1:
    if x.isinstance(x, int):
        ....
    elif isinstance(x, str)L
       ....

This should print the type of each element in your list 这应该打印列表中每个元素的类型

for item in list1:
    print type(item)

Assuming your list contains purely numbers and strings: 假设您的列表仅包含数字和字符串:

for x in list1:
    if type(x) == str:
        # do something
    else:
        # do something for numbers

Since everyone is giving answers similar to my old one (see below), I'll try something else.You can easily make 2 lists that separate ints and strings with Python's list comprehensions: 由于每个人都给出与我的旧答案相似的答案(见下文),因此我将尝试其他方法。您可以轻松地创建2个列表,这些列表使用Python的列表理解将整数和字符串分开:

strings = [x for x in list1 if isinstance(x, str)]
intlist = [x for x in list1 if isinstance(x, int)]

Using list comprehensions made the code more compact and easier to understand. 使用列表推导使代码更紧凑,更易于理解。

Old response: 旧回应:

list1 = [1, 4, 5, '5', '3', 3, 'a']
for x in list1:
    if(isinstance(x, str)):
        print(str(x) + ' is a string.')
    else:
        print(str(x) + ' is not a string.')

You could try this one, 你可以试试这个

list1=[1,2,'d','t','h',7,8]

for data in list1:
    if type(data) is str:
        #do something with it
    elif type(data) is int:
        #do something with it

you can try something like this or any of those methods mentioned from other answers in the python interpreter to see it works - 您可以尝试类似的方法或python解释器中其他答案中提到的任何方法,以查看其是否有效-

>> type(1) is str

and you would get 你会得到

>> False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM