简体   繁体   English

使用列表推导和input()的麻烦

[英]trouble with using list comprehensions & input()

Trying to write a list comprehension that can iterate through a string from input() and create a list with each character of the string having it's own index. 尝试编写一个列表解析,该迭代可以遍历input()中的字符串,并创建一个列表,其中字符串的每个字符都有其自己的索引。

In essence, I want a function that does this: 本质上,我想要一个执行此操作的函数:

x = ["00.00"[h] for h in range(len("00.00"))]
print(x)
> ['0', '0', '.', '0', '0']

When putting an actual string ("00.00") in there, python does exactly what I want it to do. 当在其中放置实际的字符串(“ 00.00”)时,python确实执行了我想要的操作。 But it refuses to take an input() the same way: 但是它拒绝采用相同的input()方法:

>>> x = [input()[h] for h in range(len(input()))]
> what

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <listcomp>
IndexError: string index out of range

The word "what" in there is what i inputted, but it does the same for basically everything else I've put in. I'm not sure what's so different about input() that changes how the indexes work. 我输入的是“ what”一词,但基本上与我输入的其他内容相同。我不确定input()的不同之处会改变索引的工作方式。 What is it? 它是什么?

You produced a rather long-winded spelling of list() . 您产生了list()相当冗长的拼写。 There is no need to use list comprehension here: 此处无需使用列表理解:

list(input())

What goes wrong for you is that the expression at the front of the list comprehension is evaluated for every single iteration ; 对您来说,出问题的是,列表理解的最前面的表达式针对每个迭代进行求值; so you call input() first to get a string, then for every character in that string you call input() again , but this time the input is not necessarily the same string. 因此,您首先调用input()以获取一个字符串,然后针对该字符串中的每个字符再次调用input() ,但这一次输入不一定是相同的字符串。

If you ever do need a list comprehension over a string, just iterate over the string directly. 如果您确实需要对字符串的列表理解,只需直接对字符串进行迭代即可。 The Python for loop is a for each construct , there is no need to generate an index; Python for循环是每个结构的 ,无需生成索引; for example, to filter the input to produce a list of lowercase ASCII letters, there is no need to use range() : 例如,要过滤输入以产生小写ASCII字母列表,则无需使用range()

[char for char in input() if 'a' <= char <= 'b']

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

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