简体   繁体   English

如何保留列表中元素的顺序,同时将其转换为 Python 中的集合以及如何在 Python 中实现“scanf()”?

[英]How to preserve the order of elements in list while converting it to set in Python and how to implement `scanf()` in Python?

Actually I have two questions:其实我有两个问题:

  1. How to preserve the order of elements in the list when converted to set?转换为集合时如何保留列表中元素的顺序? For example consider the following:例如考虑以下内容:

>>>set([7, 10, 78, 96, 13, 42, 88, 7, 12, 16])

{96, 7, 10, 42, 12, 13, 78, 16, 88}

The order was lost during conversion.订单在转换过程中丢失。 How to preserve the order?如何维护订单?

  1. How to get input without getting an error when we hit space or enter without actually entering the value?当我们按空格键或在没有实际输入值的情况下输入时,如何在不出错的情况下获取输入?

For example, if the code was like: n = int(input()) and if the input given was just <Enter> but the next line contains the actual input how to wait until a valid input is obtained?例如,如果代码是这样的: n = int(input())并且如果给出的输入只是<Enter>但下一行包含实际输入,如何等到获得有效输入?

I mean, I want like this as in C language.我的意思是,我想要像C语言那样。 If you write the code like scanf("%d",&n);如果你写像scanf("%d",&n);这样的代码then it will ignore all the spaces and Enter key presses and will get the actual input.然后它将忽略所有空格和 Enter 按键并获得实际输入。 Also, there is another feature like getting the time like scanf("%d:%d", &h, &m);此外,还有另一个功能,例如获取时间,例如scanf("%d:%d", &h, &m); which actually allows : as an input that separates two different inputs.这实际上允许:作为分隔两个不同输入的输入。

I tried the input in two different ways: First:我以两种不同的方式尝试了输入:首先:

>>>n = int(input())

Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    n = int(input())
ValueError: invalid literal for int() with base 10: ''

Second:第二:

>>> from sys import stdin
>>> n = int(stdin.readline())

Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    n = int(stdin.readline())
ValueError: invalid literal for int() with base 10: '\n'

The only noticeable difference is that stdin captures the return key while input() just captures it as an empty string.唯一明显的区别是stdin捕获返回键,而input()只是将其捕获为空字符串。 But none of them implements the scanf() function as explained above.但是它们都没有实现如上所述的scanf() function。 How to implement this?如何实施?

In order to preserve the order you cannot use the set object.But you can use frozenset .Frozen set is just an immutable version of a Python set object.为了保持顺序,您不能使用set object。但是您可以使用frozenset 。Frozen 集合只是 Python 集合 object 的不可变版本。 So it goes like this,所以事情是这样的,

>>> a = [1,2,3,4,5]
>>> b = frozenset(a)
>>> print(a)
[1, 2, 3, 4, 5]
>>> print(b)
frozenset({1, 2, 3, 4, 5})

For your second issue I suggest using this code.It doesn't break from the loop until an integer is given.对于您的第二个问题,我建议使用此代码。在给出 integer 之前,它不会从循环中中断。

>>> while 1:
    try:
        x = int(input().strip())
        break
    except ValueError:
        pass

string.strip() is used to remove all leading and trailing whitespaces in a python string.It still works without string.strip() though. string.strip() 用于删除 python 字符串中的所有前导和尾随空格。但它仍然可以在没有 string.strip() 的情况下工作。 But it doesn't account for any '\n' of string values and loops until an integer is given.但在给出 integer 之前,它不考虑任何 '\n' 字符串值和循环。

In order to seperate the inputs by the ":" character in them you can simply use string.split(":") .It returns a string with the values seperated.为了通过其中的“:”字符分隔输入,您可以简单地使用string.split(":")它返回一个带有分隔值的字符串。

>>> a = "1:2:3"
>>> b = a.split(":")
>>> print(b)
['1', '2', '3']

Hope this helps.希望这可以帮助。

Sets do not have an order (or index).集合没有顺序(或索引)。 Assuming you're converting a list to a set to remove duplicates (and converting it back to a list without sorting), convert the list to NumPy array to remove duplicates.假设您要将列表转换为集合以删除重复项(并将其转换回列表而不进行排序),请将列表转换为 NumPy 数组以删除重复项。

>>> l = [2, 5, 10, 6, 3, 10, 5, 7]
>>> l = np.array(l)    
>>> unique_index = np.unique(l, return_index = True)[-1]
>>> unique_l = [l[i] for i in sorted(unique_index)]
>>> unique_l
[2, 5, 10, 6, 3, 7]

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

相关问题 如何与列表相交并在python中设置并保留列表的顺序? - how to intersect a list and set in python and preserve the order of the list? 在pdf中将pdf转换为文本时,如何保留输入顺序? - How to preserve entry order when converting pdf to text in python? 如何对 Python 中的列表元素进行排序 - how to order the elements of a list in Python 解释这个 python while 循环如何返回列表中元素的相反顺序 - Explain how this python while loop returns the reverse order of elements in a list 如何在比较来自 2 个不同目录的图像时保留 python 中的顺序? - How to preserve order in python while comparing images from 2 different directories? 如何编写一个使用python保留出现顺序的正则表达式? - How write a regex that preserve the order of appearence with python? 如何使用列表理解在 Python 中实现内置集 - how to implement the builtin set in Python with list comprehension 如何在保留 Python 中元素的原始顺序的同时返回字符串中的项目列表 - How to return a list of items in a string while preserving the original order of elements in Python 如何在保留列表顺序的同时修改(而不是删除!)Python列表中的重复元素? - How can I modify (not remove!) duplicated elements in a Python list, while preserving their order? 如何在python列表中保留查询参数 - How to preserve query parameter in python list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM