Hướng dẫn convert list into int python - chuyển đổi danh sách thành int python

Sử dụng hàm int [] để chuyển đổi danh sách thành int trong python. Phương pháp này với danh sách hiểu trả về một giá trị số nguyên kết hợp tất cả các yếu tố của danh sách.int[] function to Convert list to int in Python. This method with a list comprehension returns one integer value that combines all elements of the list.

Mã ví dụ đơn giản Chuyển đổi [1, 2, 3] thành một số nguyên trong 123. Sử dụng danh sách hiểu để xây dựng danh sách mới với

l = [1, 2, 3]

res = [int[item] for item in l]

print[l]
print[type[l]]
1 được áp dụng cho tất cả các yếu tố.

l = [1, 2, 3]

s = [str[integer] for integer in l]
a_string = "".join[s]

res = int[a_string]

print[res]
print[type[res]]

Output::

Cách chuyển đổi tất cả các yếu tố của danh sách thành int in python

l = [1, 2, 3]

res = [int[item] for item in l]

print[l]
print[type[l]]

Hãy bình luận nếu bạn có bất kỳ nghi ngờ và đề xuất nào trong danh sách Python này cho chương trình INT.

Lưu ý: IDE: & NBSP; Pycharm & NBSP; 2021.3.3 [Phiên bản cộng đồng] IDE: PyCharm 2021.3.3 [Community Edition]

Windows 10

Python 3.10.1

Tất cả & nbsp; ví dụ python & nbsp; là trong & nbsp; Python & nbsp; 3, vì vậy có thể khác với các phiên bản Python 2 hoặc nâng cấp. Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Bằng cấp về Khoa học máy tính và Kỹ sư: Nhà phát triển ứng dụng và có nhiều ngôn ngữ lập trình kinh nghiệm. Sự nhiệt tình cho công nghệ và thích học kỹ thuật.

Nếu danh sách của bạn chứa chuỗi số nguyên thuần túy, câu trả lời được chấp nhận là cách để đi. Nó sẽ sụp đổ nếu bạn cho nó những thứ không phải là số nguyên.

Vì vậy: nếu bạn có dữ liệu có thể chứa ints, cũng có thể nổi hoặc những thứ khác - bạn có thể tận dụng chức năng của riêng mình bằng ErrorHandling:

def maybeMakeNumber[s]:
    """Returns a string 's' into a integer if possible, a float if needed or
    returns it as is."""

    # handle None, "", 0
    if not s:
        return s
    try:
        f = float[s]
        i = int[f]
        return i if f == i else f
    except ValueError:
        return s

data = ["unkind", "data", "42", 98, "47.11", "of mixed", "types"]

converted = list[map[maybeMakeNumber, data]]
print[converted]

Output:

['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']

Để xử lý các vòng lặp bên trong Iterables, bạn có thể sử dụng người trợ giúp này:

from collections.abc import Iterable, Mapping

def convertEr[iterab]:
    """Tries to convert an iterable to list of floats, ints or the original thing
    from the iterable. Converts any iterable [tuple,set, ...] to itself in output.
    Does not work for Mappings  - you would need to check abc.Mapping and handle 
    things like {1:42, "1":84} when converting them - so they come out as is."""

    if isinstance[iterab, str]:
        return maybeMakeNumber[iterab]

    if isinstance[iterab, Mapping]:
        return iterab

    if isinstance[iterab, Iterable]:
        return  iterab.__class__[convertEr[p] for p in iterab]


data = ["unkind", {1: 3,"1":42}, "data", "42", 98, "47.11", "of mixed", 
        ["0", "8", {"15", "things"}, "3.141"], "types"]

converted = convertEr[data]
print[converted]

Output:

['unkind', {1: 3, '1': 42}, 'data', 42, 98, 47.11, 'of mixed', 
 [0, 8, {'things', 15}, 3.141], 'types'] # sets are unordered, hence diffrent order

Sự xen kẽ giữa các loại dữ liệu được tạo điều kiện bởi các thư viện Python khá dễ dàng. Nhưng vấn đề chuyển đổi toàn bộ danh sách các chuỗi thành số nguyên là khá phổ biến trong lĩnh vực phát triển. Hãy để thảo luận về một vài cách để giải quyết vấn đề cụ thể này. & NBSP;

Phương pháp 1: Sử dụng Eval []

Chức năng Python Eval [] phân tích đối số biểu thức và đánh giá nó như một biểu thức python và chạy biểu thức python [mã], nếu biểu thức là biểu diễn INT, Python chuyển đổi đối số thành một số nguyên.

Python3

l = [1, 2, 3]

res = [int[item] for item in l]

print[l]
print[type[l]]
2
l = [1, 2, 3]

res = [int[item] for item in l]

print[l]
print[type[l]]
3
l = [1, 2, 3]

res = [int[item] for item in l]

print[l]
print[type[l]]
4
l = [1, 2, 3]

res = [int[item] for item in l]

print[l]
print[type[l]]
5
l = [1, 2, 3]

res = [int[item] for item in l]

print[l]
print[type[l]]
6
l = [1, 2, 3]

res = [int[item] for item in l]

print[l]
print[type[l]]
7
l = [1, 2, 3]

res = [int[item] for item in l]

print[l]
print[type[l]]
6
l = [1, 2, 3]

res = [int[item] for item in l]

print[l]
print[type[l]]
9
l = [1, 2, 3]

res = [int[item] for item in l]

print[l]
print[type[l]]
6
def maybeMakeNumber[s]:
    """Returns a string 's' into a integer if possible, a float if needed or
    returns it as is."""

    # handle None, "", 0
    if not s:
        return s
    try:
        f = float[s]
        i = int[f]
        return i if f == i else f
    except ValueError:
        return s

data = ["unkind", "data", "42", 98, "47.11", "of mixed", "types"]

converted = list[map[maybeMakeNumber, data]]
print[converted]
1__16

def maybeMakeNumber[s]:
    """Returns a string 's' into a integer if possible, a float if needed or
    returns it as is."""

    # handle None, "", 0
    if not s:
        return s
    try:
        f = float[s]
        i = int[f]
        return i if f == i else f
    except ValueError:
        return s

data = ["unkind", "data", "42", 98, "47.11", "of mixed", "types"]

converted = list[map[maybeMakeNumber, data]]
print[converted]
5
l = [1, 2, 3]

res = [int[item] for item in l]

print[l]
print[type[l]]
3
l = [1, 2, 3]

res = [int[item] for item in l]

print[l]
print[type[l]]
4
def maybeMakeNumber[s]:
    """Returns a string 's' into a integer if possible, a float if needed or
    returns it as is."""

    # handle None, "", 0
    if not s:
        return s
    try:
        f = float[s]
        i = int[f]
        return i if f == i else f
    except ValueError:
        return s

data = ["unkind", "data", "42", 98, "47.11", "of mixed", "types"]

converted = list[map[maybeMakeNumber, data]]
print[converted]
8
def maybeMakeNumber[s]:
    """Returns a string 's' into a integer if possible, a float if needed or
    returns it as is."""

    # handle None, "", 0
    if not s:
        return s
    try:
        f = float[s]
        i = int[f]
        return i if f == i else f
    except ValueError:
        return s

data = ["unkind", "data", "42", 98, "47.11", "of mixed", "types"]

converted = list[map[maybeMakeNumber, data]]
print[converted]
9
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
0
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
1
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
2
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
3

['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
4
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
5
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
6
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
7

Output:

Modified list is: [1, -4, 3, -6, 7]

Phương pháp 2: Phương pháp ngây thơ

Đây là phương pháp chung nhất tấn công bất kỳ lập trình viên nào trong khi thực hiện loại hoạt động này. Chỉ cần lặp qua toàn bộ danh sách và chuyển đổi từng chuỗi của danh sách thành int bằng cách loại đúc. & Nbsp;

Python3

['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
8
l = [1, 2, 3]

res = [int[item] for item in l]

print[l]
print[type[l]]
3
l = [1, 2, 3]

res = [int[item] for item in l]

print[l]
print[type[l]]
4
l = [1, 2, 3]

res = [int[item] for item in l]

print[l]
print[type[l]]
5
l = [1, 2, 3]

res = [int[item] for item in l]

print[l]
print[type[l]]
6
from collections.abc import Iterable, Mapping

def convertEr[iterab]:
    """Tries to convert an iterable to list of floats, ints or the original thing
    from the iterable. Converts any iterable [tuple,set, ...] to itself in output.
    Does not work for Mappings  - you would need to check abc.Mapping and handle 
    things like {1:42, "1":84} when converting them - so they come out as is."""

    if isinstance[iterab, str]:
        return maybeMakeNumber[iterab]

    if isinstance[iterab, Mapping]:
        return iterab

    if isinstance[iterab, Iterable]:
        return  iterab.__class__[convertEr[p] for p in iterab]


data = ["unkind", {1: 3,"1":42}, "data", "42", 98, "47.11", "of mixed", 
        ["0", "8", {"15", "things"}, "3.141"], "types"]

converted = convertEr[data]
print[converted]
3__

['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
0
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
1
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
2
['unkind', {1: 3, '1': 42}, 'data', 42, 98, 47.11, 'of mixed', 
 [0, 8, {'things', 15}, 3.141], 'types'] # sets are unordered, hence diffrent order
4
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
5
['unkind', {1: 3, '1': 42}, 'data', 42, 98, 47.11, 'of mixed', 
 [0, 8, {'things', 15}, 3.141], 'types'] # sets are unordered, hence diffrent order
6
l = [1, 2, 3]

res = [int[item] for item in l]

print[l]
print[type[l]]
6
['unkind', {1: 3, '1': 42}, 'data', 42, 98, 47.11, 'of mixed', 
 [0, 8, {'things', 15}, 3.141], 'types'] # sets are unordered, hence diffrent order
8
['unkind', {1: 3, '1': 42}, 'data', 42, 98, 47.11, 'of mixed', 
 [0, 8, {'things', 15}, 3.141], 'types'] # sets are unordered, hence diffrent order
9

Modified list is: [1, -4, 3, -6, 7]
0
Modified list is: [1, -4, 3, -6, 7]
1
l = [1, 2, 3]

res = [int[item] for item in l]

print[l]
print[type[l]]
3
Modified list is: [1, -4, 3, -6, 7]
3
Modified list is: [1, -4, 3, -6, 7]
4

['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
4
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
5
Modified list is: [1, -4, 3, -6, 7]
7
Modified list is: [1, -4, 3, -6, 7]
8
Modified list is: [1, -4, 3, -6, 7]
9
Modified list is: [1, 4, 3, 6, 7]
0

Output:

Modified list is: [1, 4, 3, 6, 7]

Phương pháp 3: Sử dụng danh sách hiểu & nbsp;list comprehension 

Đây chỉ là một loại bản sao của phương thức trên, chỉ được triển khai bằng cách sử dụng danh sách hiểu, một loại tốc ký mà một nhà phát triển luôn tìm kiếm. Nó tiết kiệm thời gian và độ phức tạp của việc mã hóa một giải pháp. & NBSP;

Python3

['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
8
l = [1, 2, 3]

res = [int[item] for item in l]

print[l]
print[type[l]]
3
l = [1, 2, 3]

res = [int[item] for item in l]

print[l]
print[type[l]]
4
l = [1, 2, 3]

res = [int[item] for item in l]

print[l]
print[type[l]]
5
l = [1, 2, 3]

res = [int[item] for item in l]

print[l]
print[type[l]]
6
from collections.abc import Iterable, Mapping

def convertEr[iterab]:
    """Tries to convert an iterable to list of floats, ints or the original thing
    from the iterable. Converts any iterable [tuple,set, ...] to itself in output.
    Does not work for Mappings  - you would need to check abc.Mapping and handle 
    things like {1:42, "1":84} when converting them - so they come out as is."""

    if isinstance[iterab, str]:
        return maybeMakeNumber[iterab]

    if isinstance[iterab, Mapping]:
        return iterab

    if isinstance[iterab, Iterable]:
        return  iterab.__class__[convertEr[p] for p in iterab]


data = ["unkind", {1: 3,"1":42}, "data", "42", 98, "47.11", "of mixed", 
        ["0", "8", {"15", "things"}, "3.141"], "types"]

converted = convertEr[data]
print[converted]
3__

['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
0
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
1
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
2
['unkind', {1: 3, '1': 42}, 'data', 42, 98, 47.11, 'of mixed', 
 [0, 8, {'things', 15}, 3.141], 'types'] # sets are unordered, hence diffrent order
4
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
5
['unkind', {1: 3, '1': 42}, 'data', 42, 98, 47.11, 'of mixed', 
 [0, 8, {'things', 15}, 3.141], 'types'] # sets are unordered, hence diffrent order
6
l = [1, 2, 3]

res = [int[item] for item in l]

print[l]
print[type[l]]
6
['unkind', {1: 3, '1': 42}, 'data', 42, 98, 47.11, 'of mixed', 
 [0, 8, {'things', 15}, 3.141], 'types'] # sets are unordered, hence diffrent order
8
['unkind', {1: 3, '1': 42}, 'data', 42, 98, 47.11, 'of mixed', 
 [0, 8, {'things', 15}, 3.141], 'types'] # sets are unordered, hence diffrent order
9

Modified list is: [1, -4, 3, -6, 7]
0
Modified list is: [1, -4, 3, -6, 7]
1
l = [1, 2, 3]

res = [int[item] for item in l]

print[l]
print[type[l]]
3
Modified list is: [1, -4, 3, -6, 7]
3
Modified list is: [1, -4, 3, -6, 7]
4

Output:

Modified list is : [1, 4, 3, 6, 7]

['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
4
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
5
Modified list is: [1, -4, 3, -6, 7]
7
Modified list is: [1, -4, 3, -6, 7]
8
Modified list is: [1, -4, 3, -6, 7]
9
Modified list is: [1, 4, 3, 6, 7]
0
map[] 

Phương pháp 3: Sử dụng danh sách hiểu & nbsp;

Python3

['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
8
l = [1, 2, 3]

res = [int[item] for item in l]

print[l]
print[type[l]]
3
l = [1, 2, 3]

res = [int[item] for item in l]

print[l]
print[type[l]]
4
l = [1, 2, 3]

res = [int[item] for item in l]

print[l]
print[type[l]]
5
l = [1, 2, 3]

res = [int[item] for item in l]

print[l]
print[type[l]]
6
from collections.abc import Iterable, Mapping

def convertEr[iterab]:
    """Tries to convert an iterable to list of floats, ints or the original thing
    from the iterable. Converts any iterable [tuple,set, ...] to itself in output.
    Does not work for Mappings  - you would need to check abc.Mapping and handle 
    things like {1:42, "1":84} when converting them - so they come out as is."""

    if isinstance[iterab, str]:
        return maybeMakeNumber[iterab]

    if isinstance[iterab, Mapping]:
        return iterab

    if isinstance[iterab, Iterable]:
        return  iterab.__class__[convertEr[p] for p in iterab]


data = ["unkind", {1: 3,"1":42}, "data", "42", 98, "47.11", "of mixed", 
        ["0", "8", {"15", "things"}, "3.141"], "types"]

converted = convertEr[data]
print[converted]
3__

['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
0
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
1
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
2
['unkind', {1: 3, '1': 42}, 'data', 42, 98, 47.11, 'of mixed', 
 [0, 8, {'things', 15}, 3.141], 'types'] # sets are unordered, hence diffrent order
4
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
5
['unkind', {1: 3, '1': 42}, 'data', 42, 98, 47.11, 'of mixed', 
 [0, 8, {'things', 15}, 3.141], 'types'] # sets are unordered, hence diffrent order
6
l = [1, 2, 3]

res = [int[item] for item in l]

print[l]
print[type[l]]
6
['unkind', {1: 3, '1': 42}, 'data', 42, 98, 47.11, 'of mixed', 
 [0, 8, {'things', 15}, 3.141], 'types'] # sets are unordered, hence diffrent order
8
['unkind', {1: 3, '1': 42}, 'data', 42, 98, 47.11, 'of mixed', 
 [0, 8, {'things', 15}, 3.141], 'types'] # sets are unordered, hence diffrent order
9

['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
4
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
5
Modified list is: [1, -4, 3, -6, 7]
7
Modified list is: [1, -4, 3, -6, 7]
8
Modified list is: [1, -4, 3, -6, 7]
9
Modified list is: [1, 4, 3, 6, 7]
0

Output:

Modified list is : [1, 4, 3, 6, 7]

Phương pháp 3: Sử dụng danh sách hiểu & nbsp;

Đây chỉ là một loại bản sao của phương thức trên, chỉ được triển khai bằng cách sử dụng danh sách hiểu, một loại tốc ký mà một nhà phát triển luôn tìm kiếm. Nó tiết kiệm thời gian và độ phức tạp của việc mã hóa một giải pháp. & NBSP;

Python3

['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
8
l = [1, 2, 3]

res = [int[item] for item in l]

print[l]
print[type[l]]
3
l = [1, 2, 3]

res = [int[item] for item in l]

print[l]
print[type[l]]
4
Modified list is: [1, -4, 3, -6, 7]
3
def maybeMakeNumber[s]:
    """Returns a string 's' into a integer if possible, a float if needed or
    returns it as is."""

    # handle None, "", 0
    if not s:
        return s
    try:
        f = float[s]
        i = int[f]
        return i if f == i else f
    except ValueError:
        return s

data = ["unkind", "data", "42", 98, "47.11", "of mixed", "types"]

converted = list[map[maybeMakeNumber, data]]
print[converted]
9
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
0
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
1
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
2

['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
4
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
5
Modified list is: [1, -4, 3, -6, 7]
7
Modified list is: [1, -4, 3, -6, 7]
8
Modified list is: [1, -4, 3, -6, 7]
9
Modified list is: [1, 4, 3, 6, 7]
0

['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
4
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
5
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
6
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
7

Output:

l = [1, 2, 3]

res = [int[item] for item in l]

print[l]
print[type[l]]
0

Làm thế nào để bạn thay đổi danh sách phao thành int in python?

Cách pythonic nhất để chuyển đổi danh sách Floats FS thành danh sách các số nguyên là sử dụng FS = [int [x] cho X trong FS]. Nó lặp lại trên tất cả các phần tử trong danh sách FS bằng cách sử dụng danh sách hiểu và chuyển đổi từng phần tử danh sách X thành giá trị số nguyên bằng hàm tạo int [x].fs = [int[x] for x in fs] . It iterates over all elements in the list fs using list comprehension and converts each list element x to an integer value using the int[x] constructor.

Bạn có thể chuyển đổi sang INT trong Python không?

Để chuyển đổi hoặc đúc, một chuỗi thành một số nguyên trong Python, bạn sử dụng hàm tích hợp int [].Hàm nhận được như một tham số, chuỗi ban đầu bạn muốn chuyển đổi và trả về số nguyên tương đương với giá trị bạn đã vượt qua.Cú pháp chung trông giống như thế này: int ["str"].use the int[] built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int["str"] .

Làm thế nào để bạn chia một danh sách thành số nguyên?

Để chia một chuỗi thành một danh sách các số nguyên:..
Sử dụng str.phương thức chia [] để chia chuỗi thành một danh sách các chuỗi ..
Sử dụng hàm map [] để chuyển đổi từng chuỗi thành một số nguyên ..
Sử dụng lớp Danh sách [] để chuyển đổi đối tượng MAP thành danh sách ..

Làm thế nào để bạn thay đổi kiểu dữ liệu của một danh sách trong Python?

Bất kỳ cách nào dễ dàng để thực hiện nó cho các danh sách lồng nhau, tức là thay đổi loại [['1'], ['2']] -> int.....
cho rằng nó sẽ là bản đồ [lambda SL: map [int, sl], [['1'], ['2']]] => [[1], [2]].....
Đó sẽ là bản đồ [foo, [['1'], ['2']]]] ....
Xin lỗi, bạn có thể giải thích cú pháp này không?

Bài Viết Liên Quan

Chủ Đề